toolpack-sdk 2.0.0-alpha.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Mb=Object.create;var vr=Object.defineProperty;var Nb=Object.getOwnPropertyDescriptor;var Ab=Object.getOwnPropertyNames;var Ob=Object.getPrototypeOf,Ib=Object.prototype.hasOwnProperty;var g=(n,e)=>()=>(n&&(e=n(n=0)),e);var te=(n,e)=>{for(var t in e)vr(n,t,{get:e[t],enumerable:!0})},Ea=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ab(e))!Ib.call(n,r)&&r!==t&&vr(n,r,{get:()=>e[r],enumerable:!(o=Nb(e,r))||o.enumerable});return n};var x=(n,e,t)=>(t=n!=null?Mb(Ob(n)):{},Ea(e||!n||!n.__esModule?vr(t,"default",{value:n,enumerable:!0}):t,n)),Lb=n=>Ea(vr({},"__esModule",{value:!0}),n);var c=g(()=>{"use strict"});function jb(n){return!n||typeof n!="object"?!1:["CONTEXT_WINDOW_EXCEEDED","INSUFFICIENT_CONTEXT","SUMMARIZATION_ERROR","CONTEXT_WINDOW_CONFIG_ERROR","CONVERSATION_NOT_FOUND"].includes(n.code)}function Fb(n,e){return n instanceof Sr?{shouldRetry:n.isRetryable(),shouldFallback:!0,action:n.isRetryable()?"prune":"fail",message:n.getSuggestedRecovery()}:n instanceof Cr?{shouldRetry:!1,shouldFallback:!0,action:n.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${n.strategy}`}:n instanceof Pr?{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,ve,Ce,I,W,_e,Vn,Xn,Cr,Pr,Sr,Yn,Zn,ne=g(()=>{"use strict";c();N=class extends Error{constructor(t,o,r,s){super(t);this.code=o;this.statusCode=r;this.cause=s;this.name="SDKError"}code;statusCode;cause},ve=class extends N{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},Ce=class extends N{constructor(t,o,r){super(t,"RATE_LIMIT_ERROR",429,r);this.retryAfter=o;this.name="RateLimitError"}retryAfter},I=class extends N{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},W=class extends N{constructor(e,t="PROVIDER_ERROR",o=500,r){super(e,t,o,r),this.name="ProviderError"}},_e=class extends N{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},Vn=class extends N{constructor(t,o,r){super(t,"PAGE_ERROR",502,r);this.pageUrl=o;this.name="PageError"}pageUrl},Xn=class extends N{constructor(t,o,r){super(t,"TIMEOUT_ERROR",504,r);this.phase=o;this.name="TimeoutError"}phase},Cr=class extends N{constructor(t,o,r,s,i,a){super(t,"CONTEXT_WINDOW_EXCEEDED",400,a);this.conversationId=o;this.currentTokens=r;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 iT=Object.create;var pr=Object.defineProperty;var aT=Object.getOwnPropertyDescriptor;var lT=Object.getOwnPropertyNames;var cT=Object.getPrototypeOf,pT=Object.prototype.hasOwnProperty;var g=(r,e)=>()=>(r&&(e=r(r=0)),e);var se=(r,e)=>{for(var t in e)pr(r,t,{get:e[t],enumerable:!0})},ul=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lT(e))!pT.call(r,n)&&n!==t&&pr(r,n,{get:()=>e[n],enumerable:!(o=aT(e,n))||o.enumerable});return r};var x=(r,e,t)=>(t=r!=null?iT(cT(r)):{},ul(e||!r||!r.__esModule?pr(t,"default",{value:r,enumerable:!0}):t,r)),mT=r=>ul(pr({},"__esModule",{value:!0}),r);var l=g(()=>{"use strict"});function dT(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 uT(r,e){return r instanceof ur?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof mr?{shouldRetry:!1,shouldFallback:!0,action:r.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${r.strategy}`}:r instanceof dr?{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,de,Te,I,F,Ie,xs,vs,mr,dr,ur,Cs,ks,ce=g(()=>{"use strict";l();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},de=class extends N{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},Te=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"}},F=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"}},xs=class extends N{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},vs=class extends N{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},mr=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`
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()}},Pr=class extends N{constructor(t,o,r,s,i,a){super(t,"INSUFFICIENT_CONTEXT",400,a);this.conversationId=o;this.requiredTokens=r;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()}},dr=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`
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()}},Sr=class extends N{constructor(t,o,r,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=r;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()}},ur=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=`
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()}},Yn=class extends N{constructor(t,o,r,s,i){super(t,"CONTEXT_WINDOW_CONFIG_ERROR",400,i);this.configField=o;this.providedValue=r;this.constraint=s;this.name="ContextWindowConfigError"}configField;providedValue;constraint;getDetailedReport(){return`
35
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}},Cs=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`
36
36
  Context Window Configuration Error
37
37
  ===================================
38
38
  Field: ${this.configField}
@@ -40,48 +40,48 @@ Provided Value: ${JSON.stringify(this.providedValue)}
40
40
  Constraint: ${this.constraint}
41
41
 
42
42
  Message: ${this.message}
43
- `.trim()}},Zn=class extends N{constructor(t,o,r){super(t,"CONVERSATION_NOT_FOUND",404,r);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var Aa,V,$o=g(()=>{"use strict";c();Aa={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},V={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:Aa}});function Ia(n){if(!n)return;let e=n.toLowerCase();if(e in ps)return e;console.warn(`[Toolpack Warning] Invalid log level "${n}". Falling back to "info".`)}function La(n){if(n?.enabled!==void 0&&(ct=n.enabled),n?.filePath&&(de=n.filePath),n?.level&&(_o=Ia(n.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(ct=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(de=process.env.TOOLPACK_SDK_LOG_FILE,ct=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(_o=Ia(process.env.TOOLPACK_SDK_LOG_LEVEL)||_o),process.env.TOOLPACK_SDK_LOG_CONSOLE!==void 0&&(ms=process.env.TOOLPACK_SDK_LOG_CONSOLE==="true"),n?.console!==void 0&&process.env.TOOLPACK_SDK_LOG_CONSOLE===void 0&&(ms=n.console),ct)try{de=(0,Ee.isAbsolute)(de)?de:(0,Ee.resolve)(process.cwd(),de),(0,Eo.mkdirSync)((0,Ee.dirname)(de),{recursive:!0}),(0,Eo.appendFileSync)(de,`[${new Date().toISOString()}] [INFO] [Logger] initialized level=${_o} file=${de}
44
- `)}catch(e){console.warn(`[Toolpack Warning] Failed to initialize log file "${de}": ${e.message}`),ct=!1}}function Ke(n){return ct?ps[n]<=ps[_o]:!1}function Do(n,e){if(!Ke(n))return;let o=`[${new Date().toISOString()}] [${n.toUpperCase()}] ${ja(e)}`;(0,Eo.appendFileSync)(de,o+`
45
- `),ms&&(n==="error"?console.error:n==="warn"?console.warn:console.log)(o)}function oe(n){Do("error",n)}function M(n){Do("warn",n)}function C(n){Do("info",n)}function h(n){Do("debug",n)}function De(n){Do("trace",n)}function ja(n){return n.replace(/\bsk-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bsk-proj-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bAIza[0-9A-Za-z_-]{10,}\b/g,"[REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._-]{10,}\b/g,"Bearer [REDACTED]").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(n,e=200){try{let t=typeof n=="string"?n:JSON.stringify(n),o=ja(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function se(n,e,t){Ke("debug")&&(h(`[${e}][${n}] Messages (${t.length}):`),t.forEach((o,r)=>{h(`[${e}][${n}] #${r} role=${o?.role} content=${O(o?.content,300)}`)}))}var Eo,Ee,ps,ct,_o,de,ms,P=g(()=>{"use strict";c();Eo=require("fs"),Ee=require("path"),ps={error:0,warn:1,info:2,debug:3,trace:4},ct=!1,_o="info",de=(0,Ee.join)(process.cwd(),"toolpack-sdk.log"),ms=!1});var No={};te(No,{fetchUrlAsBase64:()=>ys,getMimeType:()=>us,isDataUri:()=>fs,normalizeImagePart:()=>Qa,parseDataUri:()=>gs,readFileAsBase64:()=>hs,toDataUri:()=>Ja});function us(n){let e=Ka.extname(n).toLowerCase();return nw[e]||"application/octet-stream"}function fs(n){return n.startsWith("data:")}function gs(n){let e=n.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function Ja(n,e){return`data:${e};base64,${n}`}async function hs(n){try{return{data:(await Ha.readFile(n)).toString("base64"),mimeType:us(n)}}catch(e){throw new I(`Failed to read image file: ${n}`,e)}}async function ys(n){try{let e=await fetch(n);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let t=await e.arrayBuffer(),o=Buffer.from(t),r=e.headers.get("content-type")||"application/octet-stream";return r=r.split(";")[0].trim(),{data:o.toString("base64"),mimeType:r}}catch(e){throw new W(`Failed to download image from URL: ${n}`,"FETCH_ERROR",500,e)}}async function Qa(n){if(n.type==="image_data")return{data:n.image_data.data,mimeType:n.image_data.mimeType};if(n.type==="image_file")return await hs(n.image_file.path);if(n.type==="image_url"){let e=n.image_url.url;if(fs(e)){let t=gs(e);if(!t)throw new I(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await ys(e)}throw new I(`Unknown ImagePart type: ${n.type}`)}var Ha,Ka,nw,pt=g(()=>{"use strict";c();Ha=x(require("fs/promises"),1),Ka=x(require("path"),1);ne();nw={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var il,al,ll,cl,pl,ml=g(()=>{"use strict";c();il="fs.read_file",al="Read File",ll="Read the contents of a file at the given path. Returns the file content as a string.",cl="filesystem",pl={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 sw(n){let e=n.path,t=n.encoding||"utf-8";if(h(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!dt.existsSync(e))throw new Error(`File not found: ${e}`);if(dt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return dt.readFileSync(e,t)}var dt,ut,Cs=g(()=>{"use strict";c();dt=x(require("fs"),1);ml();P();ut={name:il,displayName:al,description:ll,parameters:pl,category:cl,execute:sw}});var dl,ul,fl,gl,hl,yl=g(()=>{"use strict";c();dl="fs.write_file",ul="Write File",fl="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.",gl="filesystem",hl={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 iw(n){let e=n.path,t=n.content,o=n.encoding||"utf-8";if(h(`[fs.write-file] execute path="${e}" encoding=${o} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=bl.dirname(e);return ft.existsSync(r)||ft.mkdirSync(r,{recursive:!0}),ft.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var ft,bl,gt,Ps=g(()=>{"use strict";c();ft=x(require("fs"),1),bl=x(require("path"),1);yl();P();gt={name:dl,displayName:ul,description:fl,parameters:hl,category:gl,execute:iw,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var wl,Tl,xl,vl,Cl,Pl=g(()=>{"use strict";c();wl="fs.append_file",Tl="Append File",xl="Append content to the end of a file. Creates the file if it does not exist.",vl="filesystem",Cl={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 aw(n){let e=n.path,t=n.content,o=n.encoding||"utf-8";if(!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=Sl.dirname(e);return ht.existsSync(r)||ht.mkdirSync(r,{recursive:!0}),ht.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var ht,Sl,yt,Ss=g(()=>{"use strict";c();ht=x(require("fs"),1),Sl=x(require("path"),1);Pl();yt={name:wl,displayName:Tl,description:xl,parameters:Cl,category:vl,execute:aw,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var kl,Rl,$l,_l,El,Dl=g(()=>{"use strict";c();kl="fs.delete_file",Rl="Delete File",$l="Remove/delete a file from the filesystem. Does not delete directories.",_l="filesystem",El={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function lw(n){let e=n.path;if(h(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");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}. Use a different tool to remove directories.`);return bt.unlinkSync(e),`File deleted successfully: ${e}`}var bt,wt,ks=g(()=>{"use strict";c();bt=x(require("fs"),1);Dl();P();wt={name:kl,displayName:Rl,description:$l,parameters:El,category:_l,execute:lw,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var Ml,Nl,Al,Ol,Il,Ll=g(()=>{"use strict";c();Ml="fs.exists",Nl="Exists",Al="Check if a file or directory exists at the given path. Returns true or false.",Ol="filesystem",Il={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function cw(n){let e=n.path;if(!e)throw new Error("path is required");let t=jl.existsSync(e);return JSON.stringify({exists:t,path:e})}var jl,Tt,Rs=g(()=>{"use strict";c();jl=x(require("fs"),1);Ll();Tt={name:Ml,displayName:Nl,description:Al,parameters:Il,category:Ol,execute:cw}});var Fl,ql,Wl,Ul,Gl,Bl=g(()=>{"use strict";c();Fl="fs.stat",ql="Stat",Wl="Get file or directory information including size, type, and modification date.",Ul="filesystem",Gl={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function pw(n){let e=n.path;if(!e)throw new Error("path is required");if(!Or.existsSync(e))throw new Error(`Path not found: ${e}`);let t=Or.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 Or,xt,$s=g(()=>{"use strict";c();Or=x(require("fs"),1);Bl();xt={name:Fl,displayName:ql,description:Wl,parameters:Gl,category:Ul,execute:pw}});var zl,Hl,Kl,Jl,Ql,Vl=g(()=>{"use strict";c();zl="fs.list_dir",Hl="List Directory",Kl="List files and directories at the given path. Optionally recurse into subdirectories.",Jl="filesystem",Ql={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 Yl(n,e,t,o=""){let r=Ve.readdirSync(n,{withFileTypes:!0});for(let s of r){let i=Xl.join(n,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&Yl(i,!0,t,a);else if(s.isFile()){let l=Ve.statSync(i);t.push({name:a,type:"file",size:l.size})}}}async function mw(n){let e=n.path,t=n.recursive===!0;if(!e)throw new Error("path is required");if(!Ve.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ve.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=[];return Yl(e,t,r),JSON.stringify(r,null,2)}var Ve,Xl,vt,_s=g(()=>{"use strict";c();Ve=x(require("fs"),1),Xl=x(require("path"),1);Vl();vt={name:zl,displayName:Hl,description:Kl,parameters:Ql,category:Jl,execute:mw}});var Zl,ec,tc,oc,rc,nc=g(()=>{"use strict";c();Zl="fs.create_dir",ec="Create Directory",tc="Create a directory at the given path. Creates parent directories recursively if they do not exist.",oc="filesystem",rc={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 dw(n){let e=n.path,t=n.recursive!==!1;if(!e)throw new Error("path is required");if(Ct.existsSync(e)){if(Ct.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Ct.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var Ct,Pt,Es=g(()=>{"use strict";c();Ct=x(require("fs"),1);nc();Pt={name:Zl,displayName:ec,description:tc,parameters:rc,category:oc,execute:dw}});var sc,ic,ac,lc,cc,pc=g(()=>{"use strict";c();sc="fs.move",ic="Move",ac="Move or rename a file or directory from one path to another.",lc="filesystem",cc={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 uw(n){let e=n.path,t=n.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Xe.existsSync(e))throw new Error(`Source not found: ${e}`);let o=mc.dirname(t);return Xe.existsSync(o)||Xe.mkdirSync(o,{recursive:!0}),Xe.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var Xe,mc,St,Ds=g(()=>{"use strict";c();Xe=x(require("fs"),1),mc=x(require("path"),1);pc();St={name:sc,displayName:ic,description:ac,parameters:cc,category:lc,execute:uw,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var dc,uc,fc,gc,hc,yc=g(()=>{"use strict";c();dc="fs.copy",uc="Copy",fc="Copy a file or directory from one path to another. Recursively copies directories.",gc="filesystem",hc={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function bc(n,e){if(ee.statSync(n).isDirectory()){ee.existsSync(e)||ee.mkdirSync(e,{recursive:!0});let o=ee.readdirSync(n);for(let r of o)bc(qo.join(n,r),qo.join(e,r))}else ee.copyFileSync(n,e)}async function fw(n){let e=n.path,t=n.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!ee.existsSync(e))throw new Error(`Source not found: ${e}`);let o=qo.dirname(t);return ee.existsSync(o)||ee.mkdirSync(o,{recursive:!0}),bc(e,t),`Copied ${ee.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var ee,qo,kt,Ms=g(()=>{"use strict";c();ee=x(require("fs"),1),qo=x(require("path"),1);yc();kt={name:dc,displayName:uc,description:fc,parameters:hc,category:gc,execute:fw,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var wc,Tc,xc,vc,Cc,Pc=g(()=>{"use strict";c();wc="fs.read_file_range",Tc="Read File Range",xc="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",vc="filesystem",Cc={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 gw(n){let e=n.path,t=n.start_line,o=n.end_line;if(!e)throw new Error("path is required");if(t==null)throw new Error("start_line is required");if(o==null)throw new Error("end_line is required");if(t<1)throw new Error("start_line must be >= 1");if(o<t)throw new Error("end_line must be >= start_line");if(!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}`);let i=Rt.readFileSync(e,"utf-8").split(`
46
- `),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
- `);return`Lines ${l}-${p} of ${a} total:
48
- ${d}`}var Rt,$t,Ns=g(()=>{"use strict";c();Rt=x(require("fs"),1);Pc();$t={name:wc,displayName:Tc,description:xc,parameters:Cc,category:vc,execute:gw}});var Sc,kc,Rc,$c,_c,Ec=g(()=>{"use strict";c();Sc="fs.search",kc="Search",Rc="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",$c="filesystem",_c={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 hw(n,e,t,o){try{let s=Ae.readFileSync(n,"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:n,line:i+1,content:a.trim()})}}catch{}}function Mc(n,e,t,o,r){let s=Ae.readdirSync(n,{withFileTypes:!0});for(let i of s){if(o.length>=r)break;let a=Dc.join(n,i.name);i.isDirectory()&&t?Mc(a,e,!0,o,r):i.isFile()&&hw(a,e,o,r)}}async function yw(n){let e=n.path,t=n.query,o=n.recursive!==!1,r=n.max_results||50,s=!!n.regex,i=!!n.case_sensitive;if(h(`[fs.search] execute path="${e}" query="${t}" recursive=${o} regex=${s} caseSensitive=${i}`),!e)throw new Error("path is required");if(!t)throw new Error("query is required");let a=t;if(s||!i){let d=t;s||(d=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let f=i?"":"i";a=new RegExp(d,f)}if(!Ae.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ae.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(Mc(e,a,o,p,r),p.length===0)return`No matches found for "${t}" in ${e}`;let m=p.length>=r?`
50
- (results capped at ${r})`:"";return JSON.stringify(p,null,2)+m}var Ae,Dc,_t,As=g(()=>{"use strict";c();Ae=x(require("fs"),1),Dc=x(require("path"),1);Ec();P();_t={name:Sc,displayName:kc,description:Rc,parameters:_c,category:$c,execute:yw}});var Nc,Ac,Oc,Ic,Lc,jc=g(()=>{"use strict";c();Nc="fs.replace_in_file",Ac="Replace In File",Oc="Find and replace text in a file. Returns the number of replacements made.",Ic="filesystem",Lc={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 bw(n){let e=n.path,t=n.search,o=n.replace;if(!e)throw new Error("path is required");if(!t)throw new Error("search is required");if(o==null)throw new Error("replace is required");if(!Oe.existsSync(e))throw new Error(`File not found: ${e}`);if(Oe.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let s=Oe.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 Oe.writeFileSync(e,l,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var Oe,Et,Os=g(()=>{"use strict";c();Oe=x(require("fs"),1);jc();Et={name:Nc,displayName:Ac,description:Oc,parameters:Lc,category:Ic,execute:bw,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 Fc,qc,Wc,Uc,Gc,Bc=g(()=>{"use strict";c();Fc="fs.tree",qc="Tree",Wc="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Uc="filesystem",Gc={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});function zc(n,e,t,o,r){if(t>o)return;let i=Dt.readdirSync(n,{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()?(r.push(`${e}${m}${l.name}/`),zc(Ir.join(n,l.name),e+d,t+1,o,r)):r.push(`${e}${m}${l.name}`)}}async function ww(n){let e=n.path,t=n.depth||3;if(!e)throw new Error("path is required");if(!Dt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Dt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${Ir.basename(e)}/`];return zc(e,"",1,t,s),s.join(`
51
- `)}var Dt,Ir,Mt,Is=g(()=>{"use strict";c();Dt=x(require("fs"),1),Ir=x(require("path"),1);Bc();Mt={name:Fc,displayName:qc,description:Wc,parameters:Gc,category:Uc,execute:ww}});var Hc,Kc,Jc,Qc,Vc,Xc=g(()=>{"use strict";c();Hc="fs.glob",Kc="Glob Pattern Match",Jc='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',Qc="filesystem",Vc={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});async function Tw(n){let e=n.pattern,t=n.cwd,o=n.ignore,r=n.onlyFiles!==!1,s=n.onlyDirectories===!0,i=n.absolute===!0;if(!e)throw new Error("pattern is required");let a=e.replace(/\\/g,"/");try{let l=await(0,Yc.default)(a,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:r,onlyDirectories:s,absolute:i,dot:!0});return JSON.stringify({pattern:e,files:l,count:l.length},null,2)}catch(l){throw new Error(`Failed to glob pattern "${e}": ${l.message}`)}}var Yc,Lr,Ls=g(()=>{"use strict";c();Yc=x(require("fast-glob"),1);Xc();Lr={name:Hc,displayName:Kc,description:Jc,parameters:Vc,category:Qc,execute:Tw}});var Zc,ep,tp,op,rp,np=g(()=>{"use strict";c();Zc="fs.delete_dir",ep="Delete Directory",tp="Delete a directory and all its contents recursively",op="filesystem",rp={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 xw(n){let e=n.path,t=n.force!==!1;if(!e)throw new Error("path is required");if(!(0,jr.existsSync)(e))throw new Error(`Directory does not exist: ${e}`);if(!(0,jr.statSync)(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await(0,sp.rm)(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(r){throw new Error(`Failed to delete directory "${e}": ${r.message}`)}}var sp,jr,Fr,js=g(()=>{"use strict";c();sp=require("fs/promises"),jr=require("fs");np();Fr={name:Zc,displayName:ep,description:tp,parameters:rp,category:op,execute:xw,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var ip,ap,lp,cp,pp,mp=g(()=>{"use strict";c();ip="fs.batch_read",ap="Batch Read Files",lp="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",cp="filesystem",pp={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 vw(n){let e=n.paths,t=n.encoding||"utf-8",o=n.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let r=[],s=0,i=0;for(let a of e)try{let l=await(0,dp.readFile)(a,t);r.push({path:a,content:l,success:!0}),s++}catch(l){let p=l.message;if(r.push({path:a,error:p,success:!1}),i++,!o)throw new Error(`Failed to read file "${a}": ${p}`)}return JSON.stringify({total:e.length,success:s,failed:i,results:r},null,2)}var dp,qr,Fs=g(()=>{"use strict";c();dp=require("fs/promises");mp();qr={name:ip,displayName:ap,description:lp,parameters:pp,category:cp,execute:vw}});var up,fp,gp,hp,yp,bp=g(()=>{"use strict";c();up="fs.batch_write",fp="Batch Write Files",gp="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",hp="filesystem",yp={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 Cw(n){let e=n.files,t=n.encoding||"utf-8",o=n.atomic!==!1,r=n.createDirs!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("files array is required and must not be empty");for(let a of e)if(!a.path||a.content===void 0)throw new Error("Each file must have path and content properties");let s=[],i=[];try{for(let a of e){let l=(0,Wr.resolve)(a.path);if(o){let p=(0,qs.existsSync)(l),m={path:l,existed:p};p&&(m.originalContent=await(0,Se.readFile)(l,t)),s.push(m)}if(r){let p=(0,Wr.dirname)(l);await(0,Se.mkdir)(p,{recursive:!0})}await(0,Se.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,Se.writeFile)(l.path,l.originalContent,t):!l.existed&&(0,qs.existsSync)(l.path)&&await(0,Se.unlink)(l.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var Se,Wr,qs,Ur,Ws=g(()=>{"use strict";c();Se=require("fs/promises"),Wr=require("path"),qs=require("fs");bp();Ur={name:up,displayName:fp,description:gp,parameters:yp,category:hp,execute:Cw,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var wp={};te(wp,{fsAppendFileTool:()=>yt,fsBatchReadTool:()=>qr,fsBatchWriteTool:()=>Ur,fsCopyTool:()=>kt,fsCreateDirTool:()=>Pt,fsDeleteDirTool:()=>Fr,fsDeleteFileTool:()=>wt,fsExistsTool:()=>Tt,fsGlobTool:()=>Lr,fsListDirTool:()=>vt,fsMoveTool:()=>St,fsReadFileRangeTool:()=>$t,fsReadFileTool:()=>ut,fsReplaceInFileTool:()=>Et,fsSearchTool:()=>_t,fsStatTool:()=>xt,fsToolsProject:()=>Us,fsTreeTool:()=>Mt,fsWriteFileTool:()=>gt});var Us,Gs=g(()=>{"use strict";c();Cs();Ps();Ss();ks();Rs();$s();_s();Es();Ds();Ms();Ns();As();Os();Is();Ls();js();Fs();Ws();Cs();Ps();Ss();ks();Rs();$s();_s();Es();Ds();Ms();Ns();As();Os();Is();Ls();js();Fs();Ws();Us={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:[ut,gt,yt,wt,Tt,xt,vt,Pt,St,kt,$t,_t,Et,Mt,Lr,Fr,qr,Ur],dependencies:{"fast-glob":"^3.3.2"}}});var Tp,xp,vp,Cp,Pp,Sp=g(()=>{"use strict";c();Tp="exec.run",xp="Run",vp="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Cp="execution",Pp={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 Pw(n){let e=n.command,t=n.cwd,o=n.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return(0,kp.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"]})||"(command completed with no output)"}catch(r){let s=r.stdout||"",i=r.stderr||"";return`Command failed (exit code ${r.status??"unknown"}):
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 yl,Z,fn=g(()=>{"use strict";l();yl={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},Z={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:yl}});function wl(r){if(!r)return;let e=r.toLowerCase();if(e in As)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function Tl(r){if(r?.enabled!==void 0&&(Ct=r.enabled),r?.filePath&&(xe=r.filePath),r?.level&&(gn=wl(r.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(Ct=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(xe=process.env.TOOLPACK_SDK_LOG_FILE,Ct=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(gn=wl(process.env.TOOLPACK_SDK_LOG_LEVEL)||gn),process.env.TOOLPACK_SDK_LOG_CONSOLE!==void 0&&(Is=process.env.TOOLPACK_SDK_LOG_CONSOLE==="true"),r?.console!==void 0&&process.env.TOOLPACK_SDK_LOG_CONSOLE===void 0&&(Is=r.console),Ct)try{xe=(0,Le.isAbsolute)(xe)?xe:(0,Le.resolve)(process.cwd(),xe),(0,hn.mkdirSync)((0,Le.dirname)(xe),{recursive:!0}),(0,hn.appendFileSync)(xe,`[${new Date().toISOString()}] [INFO] [Logger] initialized level=${gn} file=${xe}
44
+ `)}catch(e){console.warn(`[Toolpack Warning] Failed to initialize log file "${xe}": ${e.message}`),Ct=!1}}function nt(r){return Ct?As[r]<=As[gn]:!1}function yn(r,e){if(!nt(r))return;let o=`[${new Date().toISOString()}] [${r.toUpperCase()}] ${xl(e)}`;(0,hn.appendFileSync)(xe,o+`
45
+ `),Is&&(r==="error"?console.error:r==="warn"?console.warn:console.log)(o)}function pe(r){yn("error",r)}function L(r){yn("warn",r)}function P(r){yn("info",r)}function h(r){yn("debug",r)}function je(r){yn("trace",r)}function xl(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=xl(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function ee(r,e,t){nt("debug")&&(h(`[${e}][${r}] Messages (${t.length}):`),t.forEach((o,n)=>{h(`[${e}][${r}] #${n} role=${o?.role} content=${O(o?.content,300)}`)}))}var hn,Le,As,Ct,gn,xe,Is,k=g(()=>{"use strict";l();hn=require("fs"),Le=require("path"),As={error:0,warn:1,info:2,debug:3,trace:4},Ct=!1,gn="info",xe=(0,Le.join)(process.cwd(),"toolpack-sdk.log"),Is=!1});var wn={};se(wn,{fetchUrlAsBase64:()=>Ws,getMimeType:()=>Ls,isDataUri:()=>js,normalizeImagePart:()=>El,parseDataUri:()=>Fs,readFileAsBase64:()=>qs,toDataUri:()=>$l});function Ls(r){let e=_l.extname(r).toLowerCase();return DT[e]||"application/octet-stream"}function js(r){return r.startsWith("data:")}function Fs(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function $l(r,e){return`data:${e};base64,${r}`}async function qs(r){try{return{data:(await Rl.readFile(r)).toString("base64"),mimeType:Ls(r)}}catch(e){throw new I(`Failed to read image file: ${r}`,e)}}async function Ws(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 F(`Failed to download image from URL: ${r}`,"FETCH_ERROR",500,e)}}async function El(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await qs(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(js(e)){let t=Fs(e);if(!t)throw new I(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Ws(e)}throw new I(`Unknown ImagePart type: ${r.type}`)}var Rl,_l,DT,kt=g(()=>{"use strict";l();Rl=x(require("fs/promises"),1),_l=x(require("path"),1);ce();DT={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Ul,Gl,Bl,zl,Hl,Kl=g(()=>{"use strict";l();Ul="fs.read_file",Gl="Read File",Bl="Read the contents of a file at the given path. Returns the file content as a string.",zl="filesystem",Hl={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 MT(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(!St.existsSync(e))throw new Error(`File not found: ${e}`);if(St.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return St.readFileSync(e,t)}var St,Rt,Ks=g(()=>{"use strict";l();St=x(require("fs"),1);Kl();k();Rt={name:Ul,displayName:Gl,description:Bl,parameters:Hl,category:zl,execute:MT}});var Jl,Vl,Ql,Xl,Yl,Zl=g(()=>{"use strict";l();Jl="fs.write_file",Vl="Write File",Ql="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.",Xl="filesystem",Yl={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 OT(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=ec.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,ec,$t,Js=g(()=>{"use strict";l();_t=x(require("fs"),1),ec=x(require("path"),1);Zl();k();$t={name:Jl,displayName:Vl,description:Ql,parameters:Yl,category:Xl,execute:OT,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var tc,oc,nc,rc,sc,ic=g(()=>{"use strict";l();tc="fs.append_file",oc="Append File",nc="Append content to the end of a file. Creates the file if it does not exist.",rc="filesystem",sc={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 NT(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=ac.dirname(e);return Et.existsSync(n)||Et.mkdirSync(n,{recursive:!0}),Et.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Et,ac,Dt,Vs=g(()=>{"use strict";l();Et=x(require("fs"),1),ac=x(require("path"),1);ic();Dt={name:tc,displayName:oc,description:nc,parameters:sc,category:rc,execute:NT,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var lc,cc,pc,mc,dc,uc=g(()=>{"use strict";l();lc="fs.delete_file",cc="Delete File",pc="Remove/delete a file from the filesystem. Does not delete directories.",mc="filesystem",dc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function AT(r){let e=r.path;if(h(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Mt.existsSync(e))throw new Error(`File not found: ${e}`);if(Mt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Mt.unlinkSync(e),`File deleted successfully: ${e}`}var Mt,Ot,Qs=g(()=>{"use strict";l();Mt=x(require("fs"),1);uc();k();Ot={name:lc,displayName:cc,description:pc,parameters:dc,category:mc,execute:AT,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var fc,gc,hc,yc,bc,wc=g(()=>{"use strict";l();fc="fs.exists",gc="Exists",hc="Check if a file or directory exists at the given path. Returns true or false.",yc="filesystem",bc={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function IT(r){let e=r.path;if(!e)throw new Error("path is required");let t=Tc.existsSync(e);return JSON.stringify({exists:t,path:e})}var Tc,Nt,Xs=g(()=>{"use strict";l();Tc=x(require("fs"),1);wc();Nt={name:fc,displayName:gc,description:hc,parameters:bc,category:yc,execute:IT}});var xc,vc,Cc,kc,Pc,Sc=g(()=>{"use strict";l();xc="fs.stat",vc="Stat",Cc="Get file or directory information including size, type, and modification date.",kc="filesystem",Pc={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function LT(r){let e=r.path;if(!e)throw new Error("path is required");if(!Cr.existsSync(e))throw new Error(`Path not found: ${e}`);let t=Cr.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 Cr,At,Ys=g(()=>{"use strict";l();Cr=x(require("fs"),1);Sc();At={name:xc,displayName:vc,description:Cc,parameters:Pc,category:kc,execute:LT}});var Rc,_c,$c,Ec,Dc,Mc=g(()=>{"use strict";l();Rc="fs.list_dir",_c="List Directory",$c="List files and directories at the given path. Optionally recurse into subdirectories.",Ec="filesystem",Dc={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 Nc(r,e,t,o=""){let n=it.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=Oc.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&Nc(i,!0,t,a);else if(s.isFile()){let c=it.statSync(i);t.push({name:a,type:"file",size:c.size})}}}async function jT(r){let e=r.path,t=r.recursive===!0;if(!e)throw new Error("path is required");if(!it.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!it.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[];return Nc(e,t,n),JSON.stringify(n,null,2)}var it,Oc,It,Zs=g(()=>{"use strict";l();it=x(require("fs"),1),Oc=x(require("path"),1);Mc();It={name:Rc,displayName:_c,description:$c,parameters:Dc,category:Ec,execute:jT}});var Ac,Ic,Lc,jc,Fc,qc=g(()=>{"use strict";l();Ac="fs.create_dir",Ic="Create Directory",Lc="Create a directory at the given path. Creates parent directories recursively if they do not exist.",jc="filesystem",Fc={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 FT(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(Lt.existsSync(e)){if(Lt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Lt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var Lt,jt,ei=g(()=>{"use strict";l();Lt=x(require("fs"),1);qc();jt={name:Ac,displayName:Ic,description:Lc,parameters:Fc,category:jc,execute:FT}});var Wc,Uc,Gc,Bc,zc,Hc=g(()=>{"use strict";l();Wc="fs.move",Uc="Move",Gc="Move or rename a file or directory from one path to another.",Bc="filesystem",zc={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 qT(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(!at.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Kc.dirname(t);return at.existsSync(o)||at.mkdirSync(o,{recursive:!0}),at.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var at,Kc,Ft,ti=g(()=>{"use strict";l();at=x(require("fs"),1),Kc=x(require("path"),1);Hc();Ft={name:Wc,displayName:Uc,description:Gc,parameters:zc,category:Bc,execute:qT,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var Jc,Vc,Qc,Xc,Yc,Zc=g(()=>{"use strict";l();Jc="fs.copy",Vc="Copy",Qc="Copy a file or directory from one path to another. Recursively copies directories.",Xc="filesystem",Yc={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function ep(r,e){if(ie.statSync(r).isDirectory()){ie.existsSync(e)||ie.mkdirSync(e,{recursive:!0});let o=ie.readdirSync(r);for(let n of o)ep(Rn.join(r,n),Rn.join(e,n))}else ie.copyFileSync(r,e)}async function WT(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(!ie.existsSync(e))throw new Error(`Source not found: ${e}`);let o=Rn.dirname(t);return ie.existsSync(o)||ie.mkdirSync(o,{recursive:!0}),ep(e,t),`Copied ${ie.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var ie,Rn,qt,oi=g(()=>{"use strict";l();ie=x(require("fs"),1),Rn=x(require("path"),1);Zc();qt={name:Jc,displayName:Vc,description:Qc,parameters:Yc,category:Xc,execute:WT,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var tp,op,np,rp,sp,ip=g(()=>{"use strict";l();tp="fs.read_file_range",op="Read File Range",np="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",rp="filesystem",sp={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 UT(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(!Wt.existsSync(e))throw new Error(`File not found: ${e}`);if(Wt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=Wt.readFileSync(e,"utf-8").split(`
46
+ `),a=i.length,c=Math.min(t,a),p=Math.min(o,a),u=i.slice(c-1,p).map((f,b)=>`${c+b}: ${f}`).join(`
47
+ `);return`Lines ${c}-${p} of ${a} total:
48
+ ${u}`}var Wt,Ut,ni=g(()=>{"use strict";l();Wt=x(require("fs"),1);ip();Ut={name:tp,displayName:op,description:np,parameters:sp,category:rp,execute:UT}});var ap,lp,cp,pp,mp,dp=g(()=>{"use strict";l();ap="fs.search",lp="Search",cp="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",pp="filesystem",mp={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 GT(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 fp(r,e,t,o,n){let s=We.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=up.join(r,i.name);i.isDirectory()&&t?fp(a,e,!0,o,n):i.isFile()&&GT(a,e,o,n)}}async function BT(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(fp(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,up,Gt,ri=g(()=>{"use strict";l();We=x(require("fs"),1),up=x(require("path"),1);dp();k();Gt={name:ap,displayName:lp,description:cp,parameters:mp,category:pp,execute:BT}});var gp,hp,yp,bp,wp,Tp=g(()=>{"use strict";l();gp="fs.replace_in_file",hp="Replace In File",yp="Find and replace text in a file. Returns the number of replacements made.",bp="filesystem",wp={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 zT(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 c=s.split(t).join(o);return Ue.writeFileSync(e,c,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var Ue,Bt,si=g(()=>{"use strict";l();Ue=x(require("fs"),1);Tp();Bt={name:gp,displayName:hp,description:yp,parameters:wp,category:bp,execute:zT,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 xp,vp,Cp,kp,Pp,Sp=g(()=>{"use strict";l();xp="fs.tree",vp="Tree",Cp="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",kp="filesystem",Pp={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 Rp(r,e,t,o,n){if(t>o)return;let i=zt.readdirSync(r,{withFileTypes:!0}).sort((a,c)=>a.isDirectory()&&!c.isDirectory()?-1:!a.isDirectory()&&c.isDirectory()?1:a.name.localeCompare(c.name));for(let a=0;a<i.length;a++){let c=i[a],p=a===i.length-1,m=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",u=p?" ":"\u2502 ";c.isDirectory()?(n.push(`${e}${m}${c.name}/`),Rp(kr.join(r,c.name),e+u,t+1,o,n)):n.push(`${e}${m}${c.name}`)}}async function HT(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!zt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!zt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${kr.basename(e)}/`];return Rp(e,"",1,t,s),s.join(`
51
+ `)}var zt,kr,Ht,ii=g(()=>{"use strict";l();zt=x(require("fs"),1),kr=x(require("path"),1);Sp();Ht={name:xp,displayName:vp,description:Cp,parameters:Pp,category:kp,execute:HT}});var _p,$p,Ep,Dp,Mp,Op=g(()=>{"use strict";l();_p="fs.glob",$p="Glob Pattern Match",Ep='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',Dp="filesystem",Mp={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 KT(r){let e=r.pattern,t=r.cwd,o=r.ignore,n=r.onlyFiles!==!1,s=r.onlyDirectories===!0,i=r.absolute===!0;if(!e)throw new Error("pattern is required");let a=e.replace(/\\/g,"/");try{let c=await(0,Np.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:c,count:c.length},null,2)}catch(c){throw new Error(`Failed to glob pattern "${e}": ${c.message}`)}}var Np,Kt,ai=g(()=>{"use strict";l();Np=x(require("fast-glob"),1);Op();Kt={name:_p,displayName:$p,description:Ep,parameters:Mp,category:Dp,execute:KT}});var Ap,Ip,Lp,jp,Fp,qp=g(()=>{"use strict";l();Ap="fs.delete_dir",Ip="Delete Directory",Lp="Delete a directory and all its contents recursively",jp="filesystem",Fp={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 JT(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!(0,Pr.existsSync)(e))throw new Error(`Directory does not exist: ${e}`);if(!(0,Pr.statSync)(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await(0,Wp.rm)(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var Wp,Pr,Jt,li=g(()=>{"use strict";l();Wp=require("fs/promises"),Pr=require("fs");qp();Jt={name:Ap,displayName:Ip,description:Lp,parameters:Fp,category:jp,execute:JT,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var Up,Gp,Bp,zp,Hp,Kp=g(()=>{"use strict";l();Up="fs.batch_read",Gp="Batch Read Files",Bp="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",zp="filesystem",Hp={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 VT(r){let e=r.paths,t=r.encoding||"utf-8",o=r.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let n=[],s=0,i=0;for(let a of e)try{let c=await(0,Jp.readFile)(a,t);n.push({path:a,content:c,success:!0}),s++}catch(c){let p=c.message;if(n.push({path:a,error:p,success:!1}),i++,!o)throw new Error(`Failed to read file "${a}": ${p}`)}return JSON.stringify({total:e.length,success:s,failed:i,results:n},null,2)}var Jp,Vt,ci=g(()=>{"use strict";l();Jp=require("fs/promises");Kp();Vt={name:Up,displayName:Gp,description:Bp,parameters:Hp,category:zp,execute:VT}});var Vp,Qp,Xp,Yp,Zp,em=g(()=>{"use strict";l();Vp="fs.batch_write",Qp="Batch Write Files",Xp="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",Yp="filesystem",Zp={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 QT(r){let e=r.files,t=r.encoding||"utf-8",o=r.atomic!==!1,n=r.createDirs!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("files array is required and must not be empty");for(let a of e)if(!a.path||a.content===void 0)throw new Error("Each file must have path and content properties");let s=[],i=[];try{for(let a of e){let c=(0,Sr.resolve)(a.path);if(o){let p=(0,pi.existsSync)(c),m={path:c,existed:p};p&&(m.originalContent=await(0,Oe.readFile)(c,t)),s.push(m)}if(n){let p=(0,Sr.dirname)(c);await(0,Oe.mkdir)(p,{recursive:!0})}await(0,Oe.writeFile)(c,a.content,t),i.push(c)}return JSON.stringify({success:!0,written:i.length,files:i},null,2)}catch(a){if(o&&s.length>0){for(let c of s)try{c.existed&&c.originalContent!==void 0?await(0,Oe.writeFile)(c.path,c.originalContent,t):!c.existed&&(0,pi.existsSync)(c.path)&&await(0,Oe.unlink)(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var Oe,Sr,pi,Qt,mi=g(()=>{"use strict";l();Oe=require("fs/promises"),Sr=require("path"),pi=require("fs");em();Qt={name:Vp,displayName:Qp,description:Xp,parameters:Zp,category:Yp,execute:QT,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var tm={};se(tm,{fsAppendFileTool:()=>Dt,fsBatchReadTool:()=>Vt,fsBatchWriteTool:()=>Qt,fsCopyTool:()=>qt,fsCreateDirTool:()=>jt,fsDeleteDirTool:()=>Jt,fsDeleteFileTool:()=>Ot,fsExistsTool:()=>Nt,fsGlobTool:()=>Kt,fsListDirTool:()=>It,fsMoveTool:()=>Ft,fsReadFileRangeTool:()=>Ut,fsReadFileTool:()=>Rt,fsReplaceInFileTool:()=>Bt,fsSearchTool:()=>Gt,fsStatTool:()=>At,fsToolsProject:()=>di,fsTreeTool:()=>Ht,fsWriteFileTool:()=>$t});var di,ui=g(()=>{"use strict";l();Ks();Js();Vs();Qs();Xs();Ys();Zs();ei();ti();oi();ni();ri();si();ii();ai();li();ci();mi();Ks();Js();Vs();Qs();Xs();Ys();Zs();ei();ti();oi();ni();ri();si();ii();ai();li();ci();mi();di={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:[Rt,$t,Dt,Ot,Nt,At,It,jt,Ft,qt,Ut,Gt,Bt,Ht,Kt,Jt,Vt,Qt],dependencies:{"fast-glob":"^3.3.2"}}});var om,nm,rm,sm,im,am=g(()=>{"use strict";l();om="exec.run",nm="Run",rm="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",sm="execution",im={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 XT(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,lm.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
52
  STDOUT:
53
53
  ${s}
54
54
  STDERR:
55
- ${i}`}}var kp,Nt,Bs=g(()=>{"use strict";c();kp=require("child_process");Sp();P();Nt={name:Tp,displayName:xp,description:vp,parameters:Pp,category:Cp,execute:Pw,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var Rp,$p,_p,Ep,Dp,Mp=g(()=>{"use strict";c();Rp="exec.run_shell",$p="Run Shell",_p="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",Ep="execution",Dp={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 Sw(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function kw(n){let e=n.command,t=n.cwd,o=n.timeout||3e4;if(!e)throw new Error("command is required");h(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return(0,Np.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Sw()})||"(command completed with no output)"}catch(r){let s=r.stdout||"",i=r.stderr||"";return`Command failed (exit code ${r.status??"unknown"}):
55
+ ${i}`}}var lm,Xt,fi=g(()=>{"use strict";l();lm=require("child_process");am();k();Xt={name:om,displayName:nm,description:rm,parameters:im,category:sm,execute:XT,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var cm,pm,mm,dm,um,fm=g(()=>{"use strict";l();cm="exec.run_shell",pm="Run Shell",mm="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",dm="execution",um={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 YT(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}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-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return(0,gm.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:YT()})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
56
56
  STDOUT:
57
57
  ${s}
58
58
  STDERR:
59
- ${i}`}}var Np,At,zs=g(()=>{"use strict";c();Np=require("child_process");Mp();P();At={name:Rp,displayName:$p,description:_p,parameters:Dp,category:Ep,execute:kw,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});function Ap(n,e,t){let o=`proc_${Rw++}`,r={id:o,command:n,cwd:e,process:t,startedAt:new Date().toISOString(),stdout:"",stderr:""};return t.stdout?.on("data",s=>{r.stdout+=s.toString(),r.stdout.length>1e6&&(r.stdout=r.stdout.slice(-5e5))}),t.stderr?.on("data",s=>{r.stderr+=s.toString(),r.stderr.length>1e6&&(r.stderr=r.stderr.slice(-5e5))}),t.on("exit",()=>{}),Gr.set(o,r),o}function Br(n){return Gr.get(n)}function Op(n){let e=Gr.get(n);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function Ip(){return Array.from(Gr.values()).map(n=>({id:n.id,command:n.command,cwd:n.cwd,startedAt:n.startedAt,alive:n.process.exitCode===null,pid:n.process.pid}))}var Gr,Rw,Wo=g(()=>{"use strict";c();Gr=new Map,Rw=1});var Lp,jp,Fp,qp,Wp,Up=g(()=>{"use strict";c();Lp="exec.run_background",jp="Run Background",Fp="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.",qp="execution",Wp={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 $w(n){let e=n.command,t=n.cwd;if(!e)throw new Error("command is required");if(h(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let o=(0,Gp.spawn)(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),r=Ap(e,t,o);return JSON.stringify({id:r,pid:o.pid,command:e,message:`Background process started. Use exec.read_output("${r}") to read output, exec.kill("${r}") to stop.`})}var Gp,Ot,Hs=g(()=>{"use strict";c();Gp=require("child_process");Wo();Up();P();Ot={name:Lp,displayName:jp,description:Fp,parameters:Wp,category:qp,execute:$w,confirmation:{level:"high",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var Bp,zp,Hp,Kp,Jp,Qp=g(()=>{"use strict";c();Bp="exec.read_output",zp="Read Output",Hp="Read stdout and stderr from a background process started with exec.run_background.",Kp="execution",Jp={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function _w(n){let e=n.process_id;if(!e)throw new Error("process_id is required");let t=Br(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 It,Ks=g(()=>{"use strict";c();Wo();Qp();It={name:Bp,displayName:zp,description:Hp,parameters:Jp,category:Kp,execute:_w}});var Vp,Xp,Yp,Zp,em,tm=g(()=>{"use strict";c();Vp="exec.kill",Xp="Kill",Yp="Kill a background process started with exec.run_background.",Zp="execution",em={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Ew(n){let e=n.process_id;if(!e)throw new Error("process_id is required");let t=Br(e);if(!t)throw new Error(`Process not found: ${e}`);return Op(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var Lt,Js=g(()=>{"use strict";c();Wo();tm();Lt={name:Vp,displayName:Xp,description:Yp,parameters:em,category:Zp,execute:Ew,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var om,rm,nm,sm,im,am=g(()=>{"use strict";c();om="exec.list_processes",rm="List Processes",nm="List all managed background processes started with exec.run_background, including their status.",sm="execution",im={type:"object",properties:{}}});async function Dw(n){let e=Ip();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var jt,Qs=g(()=>{"use strict";c();Wo();am();jt={name:om,displayName:rm,description:nm,parameters:im,category:sm,execute:Dw}});var lm={};te(lm,{execKillTool:()=>Lt,execListProcessesTool:()=>jt,execReadOutputTool:()=>It,execRunBackgroundTool:()=>Ot,execRunShellTool:()=>At,execRunTool:()=>Nt,execToolsProject:()=>Vs});var Vs,Xs=g(()=>{"use strict";c();Bs();zs();Hs();Ks();Js();Qs();Bs();zs();Hs();Ks();Js();Qs();Vs={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:[Nt,At,Ot,It,Lt,jt],dependencies:{}}});var cm,pm,mm,dm,um,fm=g(()=>{"use strict";c();cm="system.info",pm="Info",mm="Get system information including OS, CPU, memory, and architecture.",dm="system",um={type:"object",properties:{}}});async function Mw(n){return h("[system.info] execute"),JSON.stringify({platform:L.platform(),arch:L.arch(),release:L.release(),hostname:L.hostname(),uptime:L.uptime(),cpus:{model:L.cpus()[0]?.model||"unknown",count:L.cpus().length},memory:{total:L.totalmem(),free:L.freemem(),used:L.totalmem()-L.freemem()},homedir:L.homedir(),tmpdir:L.tmpdir(),nodeVersion:process.version},null,2)}var L,Ft,Ys=g(()=>{"use strict";c();L=x(require("os"),1);fm();P();Ft={name:cm,displayName:pm,description:mm,parameters:um,category:dm,execute:Mw}});var gm,hm,ym,bm,wm,Tm=g(()=>{"use strict";c();gm="system.env",hm="Environment",ym="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",bm="system",wm={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function Nw(n){let e=n.key;if(h(`[system.env] execute key=${e??"all"}`),e){let r=process.env[e];return r===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:r})}let t={},o=Object.keys(process.env).sort();for(let r of o)process.env[r]!==void 0&&(t[r]=process.env[r]);return JSON.stringify(t,null,2)}var qt,Zs=g(()=>{"use strict";c();Tm();P();qt={name:gm,displayName:hm,description:ym,parameters:wm,category:bm,execute:Nw}});var xm,vm,Cm,Pm,Sm,km=g(()=>{"use strict";c();xm="system.set_env",vm="Set Environment",Cm="Set an environment variable for the current session. Does not persist across restarts.",Pm="system",Sm={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function Aw(n){let e=n.key,t=n.value;if(!e)throw new Error("key is required");if(t==null)throw new Error("value is required");let o=process.env[e];return process.env[e]=t,o!==void 0?`Environment variable "${e}" updated (was: "${o}", now: "${t}")`:`Environment variable "${e}" set to "${t}"`}var Wt,ei=g(()=>{"use strict";c();km();Wt={name:xm,displayName:vm,description:Cm,parameters:Sm,category:Pm,execute:Aw,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var Rm,$m,_m,Em,Dm,Mm=g(()=>{"use strict";c();Rm="system.cwd",$m="Current Directory",_m="Get the current working directory of the process.",Em="system",Dm={type:"object",properties:{}}});async function Ow(n){return h("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var Ut,ti=g(()=>{"use strict";c();Mm();P();Ut={name:Rm,displayName:$m,description:_m,parameters:Dm,category:Em,execute:Ow}});var Nm,Am,Om,Im,Lm,jm=g(()=>{"use strict";c();Nm="system.disk_usage",Am="Disk Usage",Om="Get disk usage information for a given path or the root filesystem.",Im="system",Lm={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});function oi(n){let e=["B","KB","MB","GB","TB","PB"],t=n,o=0;for(;t>=1024&&o<e.length-1;)t/=1024,o++;return`${t.toFixed(1)}${e[o]}`}async function Iw(n){let t=n.path||(process.platform==="win32"?qm.tmpdir():"/");t=zr.resolve(t);let o=process.platform==="win32";try{let r=Fm.statfsSync(t),s=BigInt(r.blocks)*BigInt(r.bsize),i=BigInt(r.bavail)*BigInt(r.bsize),a=BigInt(r.bfree)*BigInt(r.bsize),l=s-a,p=s>0?Number(l*BigInt(100)/s):0;return JSON.stringify({path:t,filesystem:"statfs",size:oi(Number(s)),used:oi(Number(l)),available:oi(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(r){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,ri.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,ri.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}: ${r?.message||r}; fallback error: ${s.message}`)}}}var Fm,qm,zr,ri,Gt,ni=g(()=>{"use strict";c();Fm=x(require("fs"),1),qm=x(require("os"),1),zr=x(require("path"),1),ri=require("child_process");jm();Gt={name:Nm,displayName:Am,description:Om,parameters:Lm,category:Im,execute:Iw}});var Wm={};te(Wm,{systemCwdTool:()=>Ut,systemDiskUsageTool:()=>Gt,systemEnvTool:()=>qt,systemInfoTool:()=>Ft,systemSetEnvTool:()=>Wt,systemToolsProject:()=>si});var si,ii=g(()=>{"use strict";c();Ys();Zs();ei();ti();ni();Ys();Zs();ei();ti();ni();si={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:[Ft,qt,Wt,Ut,Gt],dependencies:{}}});var Um,Gm,Bm,zm,Hm,Km=g(()=>{"use strict";c();Um="http.get",Gm="GET",Bm="Make an HTTP GET request to a URL and return the response body.",zm="network",Hm={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 Lw(n){let e=n.url,t=n.headers;if(h(`[http.get] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"GET",headers:t||{}}),r=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return o.ok?r.length>Jm?`${s}
61
- ${r.substring(0,Jm)}
59
+ ${i}`}}var gm,Yt,gi=g(()=>{"use strict";l();gm=require("child_process");fm();k();Yt={name:cm,displayName:pm,description:mm,parameters:um,category:dm,execute:ZT,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});function hm(r,e,t){let o=`proc_${ex++}`,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",()=>{}),Rr.set(o,n),o}function _r(r){return Rr.get(r)}function ym(r){let e=Rr.get(r);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function bm(){return Array.from(Rr.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 Rr,ex,_n=g(()=>{"use strict";l();Rr=new Map,ex=1});var wm,Tm,xm,vm,Cm,km=g(()=>{"use strict";l();wm="exec.run_background",Tm="Run Background",xm="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.",vm="execution",Cm={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 tx(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,Pm.spawn)(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),n=hm(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 Pm,Zt,hi=g(()=>{"use strict";l();Pm=require("child_process");_n();km();k();Zt={name:wm,displayName:Tm,description:xm,parameters:Cm,category:vm,execute:tx,confirmation:{level:"high",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var Sm,Rm,_m,$m,Em,Dm=g(()=>{"use strict";l();Sm="exec.read_output",Rm="Read Output",_m="Read stdout and stderr from a background process started with exec.run_background.",$m="execution",Em={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function ox(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 eo,yi=g(()=>{"use strict";l();_n();Dm();eo={name:Sm,displayName:Rm,description:_m,parameters:Em,category:$m,execute:ox}});var Mm,Om,Nm,Am,Im,Lm=g(()=>{"use strict";l();Mm="exec.kill",Om="Kill",Nm="Kill a background process started with exec.run_background.",Am="execution",Im={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function nx(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 ym(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var to,bi=g(()=>{"use strict";l();_n();Lm();to={name:Mm,displayName:Om,description:Nm,parameters:Im,category:Am,execute:nx,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var jm,Fm,qm,Wm,Um,Gm=g(()=>{"use strict";l();jm="exec.list_processes",Fm="List Processes",qm="List all managed background processes started with exec.run_background, including their status.",Wm="execution",Um={type:"object",properties:{}}});async function rx(r){let e=bm();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var oo,wi=g(()=>{"use strict";l();_n();Gm();oo={name:jm,displayName:Fm,description:qm,parameters:Um,category:Wm,execute:rx}});var Bm={};se(Bm,{execKillTool:()=>to,execListProcessesTool:()=>oo,execReadOutputTool:()=>eo,execRunBackgroundTool:()=>Zt,execRunShellTool:()=>Yt,execRunTool:()=>Xt,execToolsProject:()=>Ti});var Ti,xi=g(()=>{"use strict";l();fi();gi();hi();yi();bi();wi();fi();gi();hi();yi();bi();wi();Ti={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:[Xt,Yt,Zt,eo,to,oo],dependencies:{}}});var zm,Hm,Km,Jm,Vm,Qm=g(()=>{"use strict";l();zm="system.info",Hm="Info",Km="Get system information including OS, CPU, memory, and architecture.",Jm="system",Vm={type:"object",properties:{}}});async function sx(r){return h("[system.info] execute"),JSON.stringify({platform:q.platform(),arch:q.arch(),release:q.release(),hostname:q.hostname(),uptime:q.uptime(),cpus:{model:q.cpus()[0]?.model||"unknown",count:q.cpus().length},memory:{total:q.totalmem(),free:q.freemem(),used:q.totalmem()-q.freemem()},homedir:q.homedir(),tmpdir:q.tmpdir(),nodeVersion:process.version},null,2)}var q,no,vi=g(()=>{"use strict";l();q=x(require("os"),1);Qm();k();no={name:zm,displayName:Hm,description:Km,parameters:Vm,category:Jm,execute:sx}});var Xm,Ym,Zm,ed,td,od=g(()=>{"use strict";l();Xm="system.env",Ym="Environment",Zm="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",ed="system",td={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function ix(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 ro,Ci=g(()=>{"use strict";l();od();k();ro={name:Xm,displayName:Ym,description:Zm,parameters:td,category:ed,execute:ix}});var nd,rd,sd,id,ad,ld=g(()=>{"use strict";l();nd="system.set_env",rd="Set Environment",sd="Set an environment variable for the current session. Does not persist across restarts.",id="system",ad={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function ax(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 so,ki=g(()=>{"use strict";l();ld();so={name:nd,displayName:rd,description:sd,parameters:ad,category:id,execute:ax,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var cd,pd,md,dd,ud,fd=g(()=>{"use strict";l();cd="system.cwd",pd="Current Directory",md="Get the current working directory of the process.",dd="system",ud={type:"object",properties:{}}});async function lx(r){return h("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var io,Pi=g(()=>{"use strict";l();fd();k();io={name:cd,displayName:pd,description:md,parameters:ud,category:dd,execute:lx}});var gd,hd,yd,bd,wd,Td=g(()=>{"use strict";l();gd="system.disk_usage",hd="Disk Usage",yd="Get disk usage information for a given path or the root filesystem.",bd="system",wd={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});function Si(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 cx(r){let t=r.path||(process.platform==="win32"?vd.tmpdir():"/");t=$r.resolve(t);let o=process.platform==="win32";try{let n=xd.statfsSync(t),s=BigInt(n.blocks)*BigInt(n.bsize),i=BigInt(n.bavail)*BigInt(n.bsize),a=BigInt(n.bfree)*BigInt(n.bsize),c=s-a,p=s>0?Number(c*BigInt(100)/s):0;return JSON.stringify({path:t,filesystem:"statfs",size:Si(Number(s)),used:Si(Number(c)),available:Si(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(n){try{if(o){let c=$r.parse(t).root.replace(/\\$/,"")||"C:",p=`Get-PSDrive -Name ${c.replace(":","")} | Select-Object @{n='Drive';e={$_.Name+':'}},@{n='Used';e={$_.Used}},@{n='Free';e={$_.Free}},@{n='Total';e={$_.Used+$_.Free}} | ConvertTo-Json`,m=(0,Ri.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||`${c}`},null,2)}let s=(0,Ri.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 xd,vd,$r,Ri,ao,_i=g(()=>{"use strict";l();xd=x(require("fs"),1),vd=x(require("os"),1),$r=x(require("path"),1),Ri=require("child_process");Td();ao={name:gd,displayName:hd,description:yd,parameters:wd,category:bd,execute:cx}});var Cd={};se(Cd,{systemCwdTool:()=>io,systemDiskUsageTool:()=>ao,systemEnvTool:()=>ro,systemInfoTool:()=>no,systemSetEnvTool:()=>so,systemToolsProject:()=>$i});var $i,Ei=g(()=>{"use strict";l();vi();Ci();ki();Pi();_i();vi();Ci();ki();Pi();_i();$i={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:[no,ro,so,io,ao],dependencies:{}}});var kd,Pd,Sd,Rd,_d,$d=g(()=>{"use strict";l();kd="http.get",Pd="GET",Sd="Make an HTTP GET request to a URL and return the response body.",Rd="network",_d={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 px(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>Ed?`${s}
61
+ ${n.substring(0,Ed)}
62
62
 
63
- ... (truncated, total ${r.length} characters)`:`${s}
64
- ${r}`:`${s}
65
- ${r}`}var Jm,Bt,ai=g(()=>{"use strict";c();Km();P();Jm=1e5;Bt={name:Um,displayName:Gm,description:Bm,parameters:Hm,category:zm,execute:Lw}});var Qm,Vm,Xm,Ym,Zm,ed=g(()=>{"use strict";c();Qm="http.post",Vm="POST",Xm="Make an HTTP POST request to a URL with an optional body and return the response.",Ym="network",Zm={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 jw(n){let e=n.url,t=n.body,o=n.headers||{};if(h(`[http.post] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let r=await fetch(e,{method:"POST",headers:o,body:t||void 0}),s=await r.text(),i=`HTTP ${r.status} ${r.statusText}`;return s.length>td?`${i}
66
- ${s.substring(0,td)}
63
+ ... (truncated, total ${n.length} characters)`:`${s}
64
+ ${n}`:`${s}
65
+ ${n}`}var Ed,lo,Di=g(()=>{"use strict";l();$d();k();Ed=1e5;lo={name:kd,displayName:Pd,description:Sd,parameters:_d,category:Rd,execute:px}});var Dd,Md,Od,Nd,Ad,Id=g(()=>{"use strict";l();Dd="http.post",Md="POST",Od="Make an HTTP POST request to a URL with an optional body and return the response.",Nd="network",Ad={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 mx(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>Ld?`${i}
66
+ ${s.substring(0,Ld)}
67
67
 
68
68
  ... (truncated, total ${s.length} characters)`:`${i}
69
- ${s}`}var td,zt,li=g(()=>{"use strict";c();ed();P();td=1e5;zt={name:Qm,displayName:Vm,description:Xm,parameters:Zm,category:Ym,execute:jw,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var od,rd,nd,sd,id,ad=g(()=>{"use strict";c();od="http.put",rd="PUT",nd="Make an HTTP PUT request to a URL with an optional body and return the response.",sd="network",id={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 Fw(n){let e=n.url,t=n.body,o=n.headers||{};if(h(`[http.put] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let r=await fetch(e,{method:"PUT",headers:o,body:t||void 0}),s=await r.text(),i=`HTTP ${r.status} ${r.statusText}`;return s.length>ld?`${i}
70
- ${s.substring(0,ld)}
69
+ ${s}`}var Ld,co,Mi=g(()=>{"use strict";l();Id();k();Ld=1e5;co={name:Dd,displayName:Md,description:Od,parameters:Ad,category:Nd,execute:mx,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var jd,Fd,qd,Wd,Ud,Gd=g(()=>{"use strict";l();jd="http.put",Fd="PUT",qd="Make an HTTP PUT request to a URL with an optional body and return the response.",Wd="network",Ud={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 dx(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>Bd?`${i}
70
+ ${s.substring(0,Bd)}
71
71
 
72
72
  ... (truncated)`:`${i}
73
- ${s}`}var ld,Ht,ci=g(()=>{"use strict";c();ad();P();ld=1e5;Ht={name:od,displayName:rd,description:nd,parameters:id,category:sd,execute:Fw,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var cd,pd,md,dd,ud,fd=g(()=>{"use strict";c();cd="http.delete",pd="DELETE",md="Make an HTTP DELETE request to a URL and return the response.",dd="network",ud={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 qw(n){let e=n.url,t=n.headers;if(h(`[http.delete] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"DELETE",headers:t||{}}),r=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return r.length>gd?`${s}
74
- ${r.substring(0,gd)}
73
+ ${s}`}var Bd,po,Oi=g(()=>{"use strict";l();Gd();k();Bd=1e5;po={name:jd,displayName:Fd,description:qd,parameters:Ud,category:Wd,execute:dx,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var zd,Hd,Kd,Jd,Vd,Qd=g(()=>{"use strict";l();zd="http.delete",Hd="DELETE",Kd="Make an HTTP DELETE request to a URL and return the response.",Jd="network",Vd={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 ux(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>Xd?`${s}
74
+ ${n.substring(0,Xd)}
75
75
 
76
76
  ... (truncated)`:`${s}
77
- ${r}`}var gd,Kt,pi=g(()=>{"use strict";c();fd();P();gd=1e5;Kt={name:cd,displayName:pd,description:md,parameters:ud,category:dd,execute:qw,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var hd,yd,bd,wd,Td,xd=g(()=>{"use strict";c();hd="http.download",yd="Download",bd="Download a file from a URL and save it to a local path.",wd="network",Td={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 Ww(n){let e=n.url,t=n.path,o=n.headers;if(h(`[http.download] execute url="${e}" path="${t}"`),!e)throw new Error("url is required");if(!t)throw new Error("path is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=await fetch(e,{method:"GET",headers:o||{}});if(!r.ok)throw new Error(`Download failed: HTTP ${r.status} ${r.statusText}`);let s=Buffer.from(await r.arrayBuffer()),i=vd.dirname(t);return Jt.existsSync(i)||Jt.mkdirSync(i,{recursive:!0}),Jt.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var Jt,vd,Qt,mi=g(()=>{"use strict";c();Jt=x(require("fs"),1),vd=x(require("path"),1);xd();P();Qt={name:hd,displayName:yd,description:bd,parameters:Td,category:wd,execute:Ww}});var Cd={};te(Cd,{httpDeleteTool:()=>Kt,httpDownloadTool:()=>Qt,httpGetTool:()=>Bt,httpPostTool:()=>zt,httpPutTool:()=>Ht,httpToolsProject:()=>di});var di,ui=g(()=>{"use strict";c();ai();li();ci();pi();mi();ai();li();ci();pi();mi();di={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:[Bt,zt,Ht,Kt,Qt],dependencies:{}}});var Pd,Sd,kd,Rd,$d,_d=g(()=>{"use strict";c();Pd="github.graphql.execute",Sd="GitHub GraphQL",kd=["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(" "),Rd="github",$d={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 G(n,e){let t={Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...e||{}};return n&&(t.Authorization=`Bearer ${n}`),t}var he=g(()=>{"use strict";c()});async function B(n,e){if(e)return e;let t=process.env.GITHUB_PAT;if(t)return t;let o=process.env.GITHUB_APP_ID,r=process.env.GITHUB_APP_PRIVATE_KEY?.replace(/\\n/g,`
78
- `);if(!o||!r)throw new Error("No GitHub token available. Set GITHUB_PAT, or GITHUB_APP_ID + GITHUB_APP_PRIVATE_KEY.");let s=await Uw(o,r,n);return Gw(o,r,s)}async function Uw(n,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=Dd.get(t);if(o!==void 0)return o;let r=Nd(n,e),s=await fetch(`https://api.github.com/repos/${t}/installation`,{headers:{Authorization:`Bearer ${r}`,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 Dd.set(t,i.id),i.id}async function Gw(n,e,t){let o=Ed.get(t);if(o&&o.expiresAt>Date.now()+6e4)return o.token;let r=Nd(n,e),s=await fetch(`https://api.github.com/app/installations/${t}/access_tokens`,{method:"POST",headers:{Authorization:`Bearer ${r}`,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 Ed.set(t,{token:i.token,expiresAt:new Date(i.expires_at).getTime()}),i.token}function Nd(n,e){let t=Math.floor(Date.now()/1e3),o={alg:"RS256",typ:"JWT"},r={iat:t-30,exp:t+540,iss:n},s=l=>Buffer.from(JSON.stringify(l)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),i=`${s(o)}.${s(r)}`,a=Md.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var Md,Ed,Dd,ye=g(()=>{"use strict";c();Md=x(require("crypto"),1),Ed=new Map,Dd=new Map});async function Bw(n){let e=n.query,t=n.variables??{},o=await B(n.repo,n.token);h(`[github.graphql.execute] query_len=${e?.length??0}`);let r=await fetch("https://api.github.com/graphql",{method:"POST",headers:G(o,{"Content-Type":"application/json"}),body:JSON.stringify({query:e,variables:t})}),s=await r.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 ${r.status} ${r.statusText}
79
- ${s}`}var Vt,fi=g(()=>{"use strict";c();_d();P();he();ye();Vt={name:Pd,displayName:Sd,description:kd,parameters:$d,category:Rd,execute:Bw}});var Ad,Od,Id,Ld,jd,Fd=g(()=>{"use strict";c();Ad="github.contents.getText",Od="Get Repo File (Text)",Id="Fetch file content (decoded text) via the GitHub Contents API.",Ld="github",jd={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 zw(n){let e=n.repo,t=n.path,o=n.ref,r=await B(e,n.token),s=n.maxBytes?Number(n.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:G(r)}),p=await l.text();if(!l.ok)return`HTTP ${l.status} ${l.statusText}
80
- ${p}`;try{let d=JSON.parse(p)?.content;if(typeof d=="string"){let f=Uo.Buffer.from(d.replace(/\n/g,""),"base64").toString("utf8");if(s&&Uo.Buffer.byteLength(f,"utf8")>s){let b=Uo.Buffer.from(f,"utf8").subarray(0,s).toString("utf8"),y=`
81
- \u2026 [truncated, ${s} of ${Uo.Buffer.byteLength(f,"utf8")} bytes]`;return`HTTP ${l.status} ${l.statusText}
82
- ${b}${y}`}return`HTTP ${l.status} ${l.statusText}
83
- ${f}`}}catch{}return`HTTP ${l.status} ${l.statusText}
84
- ${p}`}var Uo,Xt,gi=g(()=>{"use strict";c();Fd();P();he();ye();Uo=require("buffer");Xt={name:Ad,displayName:Od,description:Id,parameters:jd,category:Ld,execute:zw}});var qd,Wd,Ud,Gd,Bd,zd=g(()=>{"use strict";c();qd="github.pr.reviewThreads.list",Wd="List PR Review Threads",Ud="List PR review threads via GraphQL (optionally unresolved only).",Gd="github",Bd={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 Hw(n){let[e,t]=String(n.repo).split("/"),o=Number(n.number),r=await B(n.repo,n.token),s=!!n.unresolvedOnly,i=n.first?Number(n.first):100,a=n.after?String(n.after):void 0,l=n.commentsFirst?Number(n.commentsFirst):20,p=!!n.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:G(r,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
77
+ ${n}`}var Xd,mo,Ni=g(()=>{"use strict";l();Qd();k();Xd=1e5;mo={name:zd,displayName:Hd,description:Kd,parameters:Vd,category:Jd,execute:ux,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var Yd,Zd,eu,tu,ou,nu=g(()=>{"use strict";l();Yd="http.download",Zd="Download",eu="Download a file from a URL and save it to a local path.",tu="network",ou={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 fx(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=ru.dirname(t);return uo.existsSync(i)||uo.mkdirSync(i,{recursive:!0}),uo.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var uo,ru,fo,Ai=g(()=>{"use strict";l();uo=x(require("fs"),1),ru=x(require("path"),1);nu();k();fo={name:Yd,displayName:Zd,description:eu,parameters:ou,category:tu,execute:fx}});var su={};se(su,{httpDeleteTool:()=>mo,httpDownloadTool:()=>fo,httpGetTool:()=>lo,httpPostTool:()=>co,httpPutTool:()=>po,httpToolsProject:()=>Ii});var Ii,Li=g(()=>{"use strict";l();Di();Mi();Oi();Ni();Ai();Di();Mi();Oi();Ni();Ai();Ii={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:[lo,co,po,mo,fo],dependencies:{}}});var iu,au,lu,cu,pu,mu=g(()=>{"use strict";l();iu="github.graphql.execute",au="GitHub GraphQL",lu=["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(" "),cu="github",pu={type:"object",properties:{query:{type:"string",description:"GraphQL query string"},variables:{type:"object",description:"Optional GraphQL variables"},repo:{type:"string",description:"owner/name \u2014 used for token resolution when no explicit token is provided"},token:{type:"string",description:"GitHub token (App installation or PAT). Optional \u2014 omit to auto-resolve from server credentials."}},required:["query"]}});function z(r,e){let t={Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...e||{}};return r&&(t.Authorization=`Bearer ${r}`),t}var Re=g(()=>{"use strict";l()});async function G(r,e){if(e)return e;let t=process.env.GITHUB_PAT;if(t)return t;let o=process.env.GITHUB_APP_ID,n=process.env.GITHUB_APP_PRIVATE_KEY?.replace(/\\n/g,`
78
+ `);if(!o||!n)throw new Error("No GitHub token available. Set GITHUB_PAT, or GITHUB_APP_ID + GITHUB_APP_PRIVATE_KEY.");let s=await gx(o,n,r);return hx(o,n,s)}async function gx(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=uu.get(t);if(o!==void 0)return o;let n=gu(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 uu.set(t,i.id),i.id}async function hx(r,e,t){let o=du.get(t);if(o&&o.expiresAt>Date.now()+6e4)return o.token;let n=gu(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 du.set(t,{token:i.token,expiresAt:new Date(i.expires_at).getTime()}),i.token}function gu(r,e){let t=Math.floor(Date.now()/1e3),o={alg:"RS256",typ:"JWT"},n={iat:t-30,exp:t+540,iss:r},s=c=>Buffer.from(JSON.stringify(c)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),i=`${s(o)}.${s(n)}`,a=fu.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var fu,du,uu,Ce=g(()=>{"use strict";l();fu=x(require("crypto"),1),du=new Map,uu=new Map});async function yx(r){let e=r.query,t=r.variables??{},o=await G(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:z(o,{"Content-Type":"application/json"}),body:JSON.stringify({query:e,variables:t})}),s=await n.text();try{let i=JSON.parse(s);i&&Array.isArray(i.errors)&&i.errors.length>0&&h(`[github.graphql.execute] errors=${i.errors.length}`)}catch{}return`HTTP ${n.status} ${n.statusText}
79
+ ${s}`}var go,ji=g(()=>{"use strict";l();mu();k();Re();Ce();go={name:iu,displayName:au,description:lu,parameters:pu,category:cu,execute:yx}});var hu,yu,bu,wu,Tu,xu=g(()=>{"use strict";l();hu="github.contents.getText",yu="Get Repo File (Text)",bu="Fetch file content (decoded text) via the GitHub Contents API.",wu="github",Tu={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 bx(r){let e=r.repo,t=r.path,o=r.ref,n=await G(e,r.token),s=r.maxBytes?Number(r.maxBytes):void 0,i=t.split("/").map(m=>encodeURIComponent(m)).join("/"),a=`https://api.github.com/repos/${e}/contents/${i}${o?`?ref=${encodeURIComponent(o)}`:""}`;h(`[github.contents.getText] repo=${e} path=${t} ref=${o??""}`);let c=await fetch(a,{method:"GET",headers:z(n)}),p=await c.text();if(!c.ok)return`HTTP ${c.status} ${c.statusText}
80
+ ${p}`;try{let u=JSON.parse(p)?.content;if(typeof u=="string"){let f=$n.Buffer.from(u.replace(/\n/g,""),"base64").toString("utf8");if(s&&$n.Buffer.byteLength(f,"utf8")>s){let b=$n.Buffer.from(f,"utf8").subarray(0,s).toString("utf8"),y=`
81
+ \u2026 [truncated, ${s} of ${$n.Buffer.byteLength(f,"utf8")} bytes]`;return`HTTP ${c.status} ${c.statusText}
82
+ ${b}${y}`}return`HTTP ${c.status} ${c.statusText}
83
+ ${f}`}}catch{}return`HTTP ${c.status} ${c.statusText}
84
+ ${p}`}var $n,ho,Fi=g(()=>{"use strict";l();xu();k();Re();Ce();$n=require("buffer");ho={name:hu,displayName:yu,description:bu,parameters:Tu,category:wu,execute:bx}});var vu,Cu,ku,Pu,Su,Ru=g(()=>{"use strict";l();vu="github.pr.reviewThreads.list",Cu="List PR Review Threads",ku="List PR review threads via GraphQL (optionally unresolved only).",Pu="github",Su={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 wx(r){let[e,t]=String(r.repo).split("/"),o=Number(r.number),n=await G(r.repo,r.token),s=!!r.unresolvedOnly,i=r.first?Number(r.first):100,a=r.after?String(r.after):void 0,c=r.commentsFirst?Number(r.commentsFirst):20,p=!!r.includeMeta;h(`[github.pr.reviewThreads.list] repo=${e}/${t} pr=${o} unresolvedOnly=${s} first=${i} after=${a??""} commentsFirst=${c} includeMeta=${p}`);let u=await fetch("https://api.github.com/graphql",{method:"POST",headers:z(n,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
85
85
  repository(owner:$owner,name:$name){
86
86
  pullRequest(number:$number){
87
87
  headRefOid
@@ -91,29 +91,29 @@ ${p}`}var Uo,Xt,gi=g(()=>{"use strict";c();Fd();P();he();ye();Uo=require("buffer
91
91
  }
92
92
  }
93
93
  }
94
- }`,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
- ${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},T=y?.reviewThreads?.nodes??[];if(s&&(T=T.filter(S=>S?.isResolved===!1)),p){let S={headRefOid:y?.headRefOid,threads:T,pageInfo:w};return`HTTP 200 OK
96
- ${JSON.stringify(S)}`}return`HTTP 200 OK
97
- ${JSON.stringify(T)}`}catch{return`HTTP ${d.status} ${d.statusText}
98
- ${f}`}}var Yt,hi=g(()=>{"use strict";c();zd();he();P();ye();Yt={name:qd,displayName:Wd,description:Ud,parameters:Bd,category:Gd,execute:Hw}});var Hd,Kd,Jd,Qd,Vd,Xd=g(()=>{"use strict";c();Hd="github.pr.reviewThreads.resolve",Kd="Resolve Review Thread",Jd=["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(" "),Qd="github",Vd={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 Kw(n){let e=String(n.threadId),t=await B(n.repo,n.token);h(`[github.pr.reviewThreads.resolve] threadId=${e}`);let r=await fetch("https://api.github.com/graphql",{method:"POST",headers:G(t,{"Content-Type":"application/json"}),body:JSON.stringify({query:"mutation($id:ID!){ resolveReviewThread(input:{threadId:$id}) { thread { id isResolved } } }",variables:{id:e}})}),s=await r.text();if(r.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 ${r.status} ${r.statusText}
99
- ${s}`}var Zt,yi=g(()=>{"use strict";c();Xd();he();P();ye();Zt={name:Hd,displayName:Kd,description:Jd,parameters:Vd,category:Qd,execute:Kw}});var Yd,Zd,eu,tu,ou,ru=g(()=>{"use strict";c();Yd="github.pr.reviewComments.reply",Zd="Reply to Review Comment",eu="Reply within an existing PR review thread to maintain continuity.",tu="github",ou={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 Jw(n){let e=String(n.repo),t=Number(n.number),o=Number(n.inReplyTo),r=String(n.body),s=await B(e,n.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:G(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:r})}),l=await a.text();return`HTTP ${a.status} ${a.statusText}
100
- ${l}`}var eo,bi=g(()=>{"use strict";c();ru();P();he();ye();eo={name:Yd,displayName:Zd,description:eu,parameters:ou,category:tu,execute:Jw}});var nu,su,iu,au,lu,cu=g(()=>{"use strict";c();nu="github.pr.diff.get",su="Get PR Diff",iu="Fetch the unified diff for a pull request (text/patch).",au="github",lu={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 Qw(n){let e=String(n.repo),t=Number(n.number),o=await B(e,n.token),r=n.maxBytes?Number(n.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:G(o,{Accept:"application/vnd.github.v3.diff"})}),a=await i.text();if(r&&Hr.Buffer.byteLength(a,"utf8")>r){let l=Hr.Buffer.from(a,"utf8").subarray(0,r).toString("utf8"),p=`
101
- \u2026 [truncated, ${r} of ${Hr.Buffer.byteLength(a,"utf8")} bytes]`;return`HTTP ${i.status} ${i.statusText}
102
- ${l}${p}`}return`HTTP ${i.status} ${i.statusText}
103
- ${a}`}var Hr,to,wi=g(()=>{"use strict";c();cu();he();P();ye();Hr=require("buffer");to={name:nu,displayName:su,description:iu,parameters:lu,category:au,execute:Qw}});var pu,mu,du,uu,fu,gu=g(()=>{"use strict";c();pu="github.pr.files.list",mu="List PR Files",du="List files changed in a PR with positions metadata.",uu="github",fu={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 Vw(n){let e=String(n.repo),t=Number(n.number),o=await B(e,n.token),r=n.perPage?Number(n.perPage):void 0,s=n.page?Number(n.page):void 0,i=new URLSearchParams;r&&i.set("per_page",String(r)),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=${r??""} page=${s??""}`);let l=await fetch(a,{method:"GET",headers:G(o)}),p=await l.text();return`HTTP ${l.status} ${l.statusText}
104
- ${p}`}var oo,Ti=g(()=>{"use strict";c();gu();he();P();ye();oo={name:pu,displayName:mu,description:du,parameters:fu,category:uu,execute:Vw}});var hu,yu,bu,wu,Tu,xu=g(()=>{"use strict";c();hu="github.pr.reviews.submit",yu="Submit PR Review",bu="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",wu="github",Tu={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 Xw(n){let e=String(n.repo),t=Number(n.number),o=String(n.event),r=n.body?String(n.body):void 0,s=Array.isArray(n.comments)?n.comments:void 0,i=await B(e,n.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};r&&(l.body=r),s&&s.length>0&&(l.comments=s);let p=await fetch(a,{method:"POST",headers:G(i,{"Content-Type":"application/json"}),body:JSON.stringify(l)}),m=await p.text();return`HTTP ${p.status} ${p.statusText}
105
- ${m}`}var ro,xi=g(()=>{"use strict";c();xu();he();P();ye();ro={name:hu,displayName:yu,description:bu,parameters:Tu,category:wu,execute:Xw}});var vu,Cu,Pu,Su,ku,Ru=g(()=>{"use strict";c();vu="github.issues.comments.create",Cu="Create Issue/PR Comment",Pu="Create a comment on an issue or pull request (conversation tab).",Su="github",ku={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 Yw(n){let e=String(n.repo),t=Number(n.number),o=String(n.body),r=await B(e,n.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:G(r,{"Content-Type":"application/json"}),body:JSON.stringify({body:o})}),a=await i.text();return`HTTP ${i.status} ${i.statusText}
106
- ${a}`}var Kr,vi=g(()=>{"use strict";c();Ru();he();P();ye();Kr={name:vu,displayName:Cu,description:Pu,parameters:ku,category:Su,execute:Yw}});var $u={};te($u,{githubContentsGetTextTool:()=>Xt,githubGraphqlExecuteTool:()=>Vt,githubIssuesCommentsCreateTool:()=>Kr,githubPrDiffGetTool:()=>to,githubPrFilesListTool:()=>oo,githubPrReviewCommentsReplyTool:()=>eo,githubPrReviewThreadsListTool:()=>Yt,githubPrReviewThreadsResolveTool:()=>Zt,githubPrReviewsSubmitTool:()=>ro,githubToolsProject:()=>Ci});var Ci,Pi=g(()=>{"use strict";c();fi();gi();hi();yi();bi();wi();Ti();xi();vi();fi();gi();hi();yi();bi();wi();Ti();xi();vi();Ci={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:[Vt,Xt,Yt,Zt,eo,to,oo,ro,Kr],dependencies:{}}});var _u,Eu,Du,Mu,Nu,Au=g(()=>{"use strict";c();_u="web.fetch",Eu="Fetch",Du="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).",Mu="network",Nu={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 Ou(n,e){let t=Si.load(n);t("script, style, nav, header, footer, aside, .advertisement, .ad, .sidebar").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||t('meta[property="og:title"]').attr("content")||"Untitled",r=t('meta[name="author"]').attr("content")||t('meta[property="article:author"]').attr("content")||t(".author").first().text().trim()||void 0,s=t('meta[property="article:published_time"]').attr("content")||t("time").first().attr("datetime")||t(".date, .published").first().text().trim()||void 0,i=["article","main",'[role="main"]',".content",".article-content",".post-content","#content"],a="";for(let b of i){let 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
-
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 d=a.split(/\s+/).length,f=a.split(/\s+/);return f.length>2e3&&(a=f.slice(0,2e3).join(" ")+"..."),{title:o,url:e,author:r,publishDate:s,excerpt:p.substring(0,1e3),mainContent:a.substring(0,1e4),keyPoints:m,wordCount:d}}function Iu(n,e){let t=Si.load(n);t("script, style, nav, header, footer").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||"Untitled",r=t('meta[name="description"]').attr("content")||t('meta[property="og:description"]').attr("content")||"";return r||t("p").each((s,i)=>{let a=t(i).text().trim();a.length>50&&!r&&(r=a)}),r||(r=t("body").text().trim().replace(/\s+/g," ")),{title:o,url:e,snippet:r.substring(0,500)}}function Lu(n){let e=[];return e.push(`# ${n.title}`),e.push(`URL: ${n.url}`),n.author&&e.push(`Author: ${n.author}`),n.publishDate&&e.push(`Published: ${n.publishDate}`),e.push(`Word Count: ${n.wordCount}`),e.push(""),n.keyPoints.length>0&&(e.push("## Key Points"),n.keyPoints.forEach(t=>{e.push(`- ${t}`)}),e.push("")),e.push("## Excerpt"),e.push(n.excerpt),e.push(""),e.push("## Main Content"),e.push(n.mainContent),e.join(`
109
- `)}function ju(n){return`# ${n.title}
110
- URL: ${n.url}
111
-
112
- ${n.snippet}`}var Si,Fu=g(()=>{"use strict";c();Si=x(require("cheerio"),1)});async function Zw(n){let e=n.url,t=n.extractionMode||"full",o=n.headers,r=n.timeout||3e4;if(h(`[web.fetch] execute url="${e}" mode=${t} timeout=${r}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let s=new AbortController,i=setTimeout(()=>s.abort(),r),a;try{a=await fetch(e,{method:"GET",headers:o||{},signal:s.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${r}ms`):p}finally{clearTimeout(i)}if(!a.ok)return`HTTP ${a.status} ${a.statusText}
113
- ${await a.text()}`;let l=await a.text();if(t==="structured"){let p=Ou(l,e);return Lu(p)}else if(t==="minimal"){let p=Iu(l,e);return ju(p)}else return l.length>15e3?l.substring(0,15e3)+`
114
-
115
- [TRUNCATED: showing 15K of ${l.length} total characters]`:l}var no,ki=g(()=>{"use strict";c();Au();Fu();P();no={name:_u,displayName:Eu,description:Du,parameters:Nu,category:Mu,execute:Zw}});var qu,Wu,Uu,Gu,Bu,zu=g(()=>{"use strict";c();qu="web.search",Wu="Search",Uu="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.",Gu="network",Bu={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});function Go(n){let e=Ju(n);if(!Ie.existsSync(e))return{};try{let t=Ie.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function so(n){let e=Go(n),t=eT(e.tools||e);return h(JSON.stringify(t??{})),t}function Ku(n,e){let t=Ju(e),o={};try{Ie.existsSync(t)&&(o=JSON.parse(Ie.readFileSync(t,"utf-8")))}catch{o={}}o.tools=n,Ie.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function eT(n){let e=n.additionalConfigurations||{};return e.webSearch||(e.webSearch={}),!e.webSearch.tavilyApiKey&&process.env.TOOLPACK_TAVILY_API_KEY&&(e.webSearch.tavilyApiKey=process.env.TOOLPACK_TAVILY_API_KEY),!e.webSearch.braveApiKey&&process.env.TOOLPACK_BRAVE_API_KEY&&(e.webSearch.braveApiKey=process.env.TOOLPACK_BRAVE_API_KEY),{enabled:n.enabled??V.enabled,autoExecute:n.autoExecute??V.autoExecute,maxToolRounds:n.maxToolRounds??V.maxToolRounds,toolChoicePolicy:n.toolChoicePolicy??V.toolChoicePolicy,resultMaxChars:n.resultMaxChars??V.resultMaxChars,intelligentToolDetection:n.intelligentToolDetection,enabledTools:n.enabledTools??V.enabledTools,enabledToolCategories:n.enabledToolCategories??V.enabledToolCategories,toolSearch:n.toolSearch??V.toolSearch,additionalConfigurations:e}}function Ju(n){return n?n.endsWith(".json")?Jr.resolve(n):Jr.resolve(n,Hu):Jr.resolve(process.cwd(),Hu)}var Ie,Jr,Hu,Ri=g(()=>{"use strict";c();Ie=x(require("fs"),1),Jr=x(require("path"),1);$o();P();Hu="toolpack.config.json"});function rT(n,e){h("[web.search] Parsing DuckDuckGo Lite response");let t=Vu.load(n),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 nT(n){if(n)switch(n){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function Qu(n){if(!n)return"";switch(n){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return""}}async function sT(n){let e=n.query,t=n.max_results||5,o=n.include_answer||!1,r=n.freshness;h(`[web.search] execute query="${e}" max_results=${t} includeAnswer=${o} freshness=${r??"none"}`);let s=`Request timed out after ${n.timeout||3e4}ms`,i=()=>{let d=new AbortController,f=setTimeout(()=>d.abort(),n.timeout||3e4);return{signal:d.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:d,clear:f}=i(),b=nT(r),y={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:a.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:o,...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 T=await w.json();if(T.results&&T.results.length>0){let S=T.results.map(v=>({title:v.title,link:v.url,snippet:v.content}));return o&&T.answer?JSON.stringify({answer:T.answer,results:S},null,2):JSON.stringify(S,null,2)}}else oe(`[web.search] Tavily search failed with status ${w.status}`)}catch(d){oe(`[web.search] Tavily search failed, falling back: ${d}`)}}if(a.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:d,clear:f}=i();if(o){let b=Qu(r),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 T=await w.json(),S=T.summarizer?.key;if(S&&T.web?.results){let{signal:v,clear:D}=i(),F=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${S}`,{headers:{Accept:"application/json","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:v}).finally(D);if(F.ok){let k=await F.json(),$=T.web.results.slice(0,t).map(E=>({title:E.title,link:E.url,snippet:E.description})),_=k.summary?.map(E=>E.data).join(`
116
- `)||k.title;return JSON.stringify({answer:_,results:$},null,2)}}if(T.web?.results){let v=T.web.results.slice(0,t).map(D=>({title:D.title,link:D.url,snippet:D.description}));return JSON.stringify(v,null,2)}}}else{let b=Qu(r),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 T=await w.json();if(T.web?.results&&T.web.results.length>0){let S=T.web.results.slice(0,t).map(v=>({title:v.title,link:v.url,snippet:v.description}));return JSON.stringify(S,null,2)}}}}catch(d){M(`[web.search] Brave search failed, falling back: ${d}`)}let{signal:l,clear:p}=i(),m;try{m=await fetch(tT,{method:"POST",headers:{"User-Agent":oT,"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=rT(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 Vu,tT,oT,io,$i=g(()=>{"use strict";c();Vu=x(require("cheerio"),1);zu();Ri();P();tT="https://lite.duckduckgo.com/lite/",oT="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";io={name:qu,displayName:Wu,description:Uu,parameters:Bu,category:Gu,execute:sT}});var Xu,Yu,Zu,ef,tf,of=g(()=>{"use strict";c();Xu="web.scrape",Yu="Scrape",Zu="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.",ef="network",tf={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 lT(n){let e=n.url,t=n.selector,o=n.section,r=n.format||"text",s=n.max_length||6e3,i=n.timeout||3e4;if(h(`[web.scrape] execute url="${e}" format=${r} selector=${t??"none"} section=${o??"none"} timeout=${i}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let a=new AbortController,l=setTimeout(()=>a.abort(),i),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":iT},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=sf.load(m);for(let y of aT)d(y).remove();if(r==="tables"){let y=[];return d("table").each((w,T)=>{let S=[],v=[];d(T).find("th").each((D,F)=>{v.push(d(F).text().trim())}),d(T).find("tr").each((D,F)=>{let k=v.length>0?{}:[],$=d(F).find("td");$.length>0&&($.each((_,E)=>{let U=d(E).text().trim();v.length>0&&v[_]?k[v[_]]=U:k.push(U)}),S.push(k))}),S.length>0&&y.push({id:`Table ${w+1}`,headers:v.length>0?v:void 0,rows:S})}),y.length===0?`No tables found on ${e}`:JSON.stringify(y,null,2)}let f="";if(o){let y=o.toLowerCase(),w=null,T=0;if(d("h1, h2, h3, h4, h5, h6").each((S,v)=>{if(d(v).text().toLowerCase().includes(y))return w=v,T=parseInt(v.tagName.charAt(1)),!1}),w){let S=d(w),v=[],D=S.next();for(;D.length>0;){let F=D.prop("tagName")?.toLowerCase();if(F&&/^h[1-6]$/.test(F)&&parseInt(F.charAt(1))<=T)break;let k=D.text().trim();k&&v.push(k),D=D.next()}v.length>0?(f=v.join(`
94
+ }`,variables:{owner:e,name:t,number:o,first:i,after:a,commentsFirst:c}})}),f=await u.text();if(!u.ok)return`HTTP ${u.status} ${u.statusText}
95
+ ${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},v=y?.reviewThreads?.nodes??[];if(s&&(v=v.filter(C=>C?.isResolved===!1)),p){let C={headRefOid:y?.headRefOid,threads:v,pageInfo:w};return`HTTP 200 OK
96
+ ${JSON.stringify(C)}`}return`HTTP 200 OK
97
+ ${JSON.stringify(v)}`}catch{return`HTTP ${u.status} ${u.statusText}
98
+ ${f}`}}var yo,qi=g(()=>{"use strict";l();Ru();Re();k();Ce();yo={name:vu,displayName:Cu,description:ku,parameters:Su,category:Pu,execute:wx}});var _u,$u,Eu,Du,Mu,Ou=g(()=>{"use strict";l();_u="github.pr.reviewThreads.resolve",$u="Resolve Review Thread",Eu=["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(" "),Du="github",Mu={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 Tx(r){let e=String(r.threadId),t=await G(r.repo,r.token);h(`[github.pr.reviewThreads.resolve] threadId=${e}`);let n=await fetch("https://api.github.com/graphql",{method:"POST",headers:z(t,{"Content-Type":"application/json"}),body:JSON.stringify({query:"mutation($id:ID!){ resolveReviewThread(input:{threadId:$id}) { thread { id isResolved } } }",variables:{id:e}})}),s=await n.text();if(n.ok)try{if(JSON.parse(s).errors?.find(c=>c.type==="FORBIDDEN"))return["TOOL_UNSUPPORTED_FOR_TOKEN_TYPE: resolveReviewThread is not available for GitHub App installation tokens (ghs_*).","GitHub requires a user identity (PAT with repo scope) for this operation.","Fallback action: post a reply on the thread acknowledging the fix and ask the author to resolve it manually."].join(" ")}catch{}return`HTTP ${n.status} ${n.statusText}
99
+ ${s}`}var bo,Wi=g(()=>{"use strict";l();Ou();Re();k();Ce();bo={name:_u,displayName:$u,description:Eu,parameters:Mu,category:Du,execute:Tx}});var Nu,Au,Iu,Lu,ju,Fu=g(()=>{"use strict";l();Nu="github.pr.reviewComments.reply",Au="Reply to Review Comment",Iu="Reply within an existing PR review thread to maintain continuity.",Lu="github",ju={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 xx(r){let e=String(r.repo),t=Number(r.number),o=Number(r.inReplyTo),n=String(r.body),s=await G(e,r.token),i=`https://api.github.com/repos/${e}/pulls/${t}/comments/${o}/replies`;h(`[github.pr.reviewComments.reply] repo=${e} inReplyTo=${o}`);let a=await fetch(i,{method:"POST",headers:z(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),c=await a.text();return`HTTP ${a.status} ${a.statusText}
100
+ ${c}`}var wo,Ui=g(()=>{"use strict";l();Fu();k();Re();Ce();wo={name:Nu,displayName:Au,description:Iu,parameters:ju,category:Lu,execute:xx}});var qu,Wu,Uu,Gu,Bu,zu=g(()=>{"use strict";l();qu="github.pr.diff.get",Wu="Get PR Diff",Uu="Fetch the unified diff for a pull request (text/patch).",Gu="github",Bu={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 vx(r){let e=String(r.repo),t=Number(r.number),o=await G(e,r.token),n=r.maxBytes?Number(r.maxBytes):void 0,s=`https://api.github.com/repos/${e}/pulls/${t}`;h(`[github.pr.diff.get] repo=${e} pr=${t}`);let i=await fetch(s,{method:"GET",headers:z(o,{Accept:"application/vnd.github.v3.diff"})}),a=await i.text();if(n&&Er.Buffer.byteLength(a,"utf8")>n){let c=Er.Buffer.from(a,"utf8").subarray(0,n).toString("utf8"),p=`
101
+ \u2026 [truncated, ${n} of ${Er.Buffer.byteLength(a,"utf8")} bytes]`;return`HTTP ${i.status} ${i.statusText}
102
+ ${c}${p}`}return`HTTP ${i.status} ${i.statusText}
103
+ ${a}`}var Er,To,Gi=g(()=>{"use strict";l();zu();Re();k();Ce();Er=require("buffer");To={name:qu,displayName:Wu,description:Uu,parameters:Bu,category:Gu,execute:vx}});var Hu,Ku,Ju,Vu,Qu,Xu=g(()=>{"use strict";l();Hu="github.pr.files.list",Ku="List PR Files",Ju="List files changed in a PR with positions metadata.",Vu="github",Qu={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 Cx(r){let e=String(r.repo),t=Number(r.number),o=await G(e,r.token),n=r.perPage?Number(r.perPage):void 0,s=r.page?Number(r.page):void 0,i=new URLSearchParams;n&&i.set("per_page",String(n)),s&&i.set("page",String(s));let a=`https://api.github.com/repos/${e}/pulls/${t}/files${i.toString()?`?${i.toString()}`:""}`;h(`[github.pr.files.list] repo=${e} pr=${t} perPage=${n??""} page=${s??""}`);let c=await fetch(a,{method:"GET",headers:z(o)}),p=await c.text();return`HTTP ${c.status} ${c.statusText}
104
+ ${p}`}var xo,Bi=g(()=>{"use strict";l();Xu();Re();k();Ce();xo={name:Hu,displayName:Ku,description:Ju,parameters:Qu,category:Vu,execute:Cx}});var Yu,Zu,ef,tf,of,nf=g(()=>{"use strict";l();Yu="github.pr.reviews.submit",Zu="Submit PR Review",ef="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",tf="github",of={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 kx(r){let e=String(r.repo),t=Number(r.number),o=String(r.event),n=r.body?String(r.body):void 0,s=Array.isArray(r.comments)?r.comments:void 0,i=await G(e,r.token),a=`https://api.github.com/repos/${e}/pulls/${t}/reviews`;h(`[github.pr.reviews.submit] repo=${e} pr=${t} event=${o} comments=${s?.length??0}`);let c={event:o};n&&(c.body=n),s&&s.length>0&&(c.comments=s);let p=await fetch(a,{method:"POST",headers:z(i,{"Content-Type":"application/json"}),body:JSON.stringify(c)}),m=await p.text();return`HTTP ${p.status} ${p.statusText}
105
+ ${m}`}var vo,zi=g(()=>{"use strict";l();nf();Re();k();Ce();vo={name:Yu,displayName:Zu,description:ef,parameters:of,category:tf,execute:kx}});var rf,sf,af,lf,cf,pf=g(()=>{"use strict";l();rf="github.issues.comments.create",sf="Create Issue/PR Comment",af="Create a comment on an issue or pull request (conversation tab).",lf="github",cf={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 Px(r){let e=String(r.repo),t=Number(r.number),o=String(r.body),n=await G(e,r.token),s=`https://api.github.com/repos/${e}/issues/${t}/comments`;h(`[github.issues.comments.create] repo=${e} number=${t}`);let i=await fetch(s,{method:"POST",headers:z(n,{"Content-Type":"application/json"}),body:JSON.stringify({body:o})}),a=await i.text();return`HTTP ${i.status} ${i.statusText}
106
+ ${a}`}var Co,Hi=g(()=>{"use strict";l();pf();Re();k();Ce();Co={name:rf,displayName:sf,description:af,parameters:cf,category:lf,execute:Px}});var mf={};se(mf,{githubContentsGetTextTool:()=>ho,githubGraphqlExecuteTool:()=>go,githubIssuesCommentsCreateTool:()=>Co,githubPrDiffGetTool:()=>To,githubPrFilesListTool:()=>xo,githubPrReviewCommentsReplyTool:()=>wo,githubPrReviewThreadsListTool:()=>yo,githubPrReviewThreadsResolveTool:()=>bo,githubPrReviewsSubmitTool:()=>vo,githubToolsProject:()=>Ki});var Ki,Ji=g(()=>{"use strict";l();ji();Fi();qi();Wi();Ui();Gi();Bi();zi();Hi();ji();Fi();qi();Wi();Ui();Gi();Bi();zi();Hi();Ki={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:[go,ho,yo,bo,wo,To,xo,vo,Co],dependencies:{}}});var df,uf,ff,gf,hf,yf=g(()=>{"use strict";l();df="web.fetch",uf="Fetch",ff="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).",gf="network",hf={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 bf(r,e){let t=Vi.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 c=[];t("p").each((b,y)=>{let w=t(y).text().trim();w.length>50&&c.length<3&&c.push(w)});let p=c.join(`
107
+
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 wf(r,e){let t=Vi.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 Tf(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 xf(r){return`# ${r.title}
110
+ URL: ${r.url}
111
+
112
+ ${r.snippet}`}var Vi,vf=g(()=>{"use strict";l();Vi=x(require("cheerio"),1)});async function Sx(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 c=await a.text();if(t==="structured"){let p=bf(c,e);return Tf(p)}else if(t==="minimal"){let p=wf(c,e);return xf(p)}else return c.length>15e3?c.substring(0,15e3)+`
114
+
115
+ [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var ko,Qi=g(()=>{"use strict";l();yf();vf();k();ko={name:df,displayName:uf,description:ff,parameters:hf,category:gf,execute:Sx}});var Cf,kf,Pf,Sf,Rf,_f=g(()=>{"use strict";l();Cf="web.search",kf="Search",Pf="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.",Sf="network",Rf={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 En(r){let e=Df(r);if(!Ge.existsSync(e))return{};try{let t=Ge.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Po(r){let e=En(r),t=Rx(e.tools||e);return h(JSON.stringify(t??{})),t}function Ef(r,e){let t=Df(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 Rx(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??Z.enabled,autoExecute:r.autoExecute??Z.autoExecute,maxToolRounds:r.maxToolRounds??Z.maxToolRounds,toolChoicePolicy:r.toolChoicePolicy??Z.toolChoicePolicy,resultMaxChars:r.resultMaxChars??Z.resultMaxChars,enabledTools:r.enabledTools??Z.enabledTools,enabledToolCategories:r.enabledToolCategories??Z.enabledToolCategories,toolSearch:r.toolSearch??Z.toolSearch,additionalConfigurations:e}}function Df(r){return r?r.endsWith(".json")?Dr.resolve(r):Dr.resolve(r,$f):Dr.resolve(process.cwd(),$f)}var Ge,Dr,$f,Xi=g(()=>{"use strict";l();Ge=x(require("fs"),1),Dr=x(require("path"),1);fn();k();$f="toolpack.config.json"});function Ex(r,e){h("[web.search] Parsing DuckDuckGo Lite response");let t=Of.load(r),o=[];return t("a.result-link").each((s,i)=>{if(o.length>=e)return;let a=t(i),c=a.text().trim(),p=a.attr("href"),m=a.siblings(".result-snippet").text().trim();m||(m=a.parent().text().replace(c,"").trim()),c&&p&&o.push({title:c,link:p,snippet:m.slice(0,200)})}),o}function Dx(r){if(r)switch(r){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function Mf(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 Mx(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=Po();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=Dx(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 v=await w.json();if(v.results&&v.results.length>0){let C=v.results.map(T=>({title:T.title,link:T.url,snippet:T.content}));return o&&v.answer?JSON.stringify({answer:v.answer,results:C},null,2):JSON.stringify(C,null,2)}}else pe(`[web.search] Tavily search failed with status ${w.status}`)}catch(u){pe(`[web.search] Tavily search failed, falling back: ${u}`)}}if(a.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:u,clear:f}=i();if(o){let b=Mf(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 v=await w.json(),C=v.summarizer?.key;if(C&&v.web?.results){let{signal:T,clear:R}=i(),D=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${C}`,{headers:{Accept:"application/json","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:T}).finally(R);if(D.ok){let M=await D.json(),S=v.web.results.slice(0,t).map(_=>({title:_.title,link:_.url,snippet:_.description})),$=M.summary?.map(_=>_.data).join(`
116
+ `)||M.title;return JSON.stringify({answer:$,results:S},null,2)}}if(v.web?.results){let T=v.web.results.slice(0,t).map(R=>({title:R.title,link:R.url,snippet:R.description}));return JSON.stringify(T,null,2)}}}else{let b=Mf(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 v=await w.json();if(v.web?.results&&v.web.results.length>0){let C=v.web.results.slice(0,t).map(T=>({title:T.title,link:T.url,snippet:T.description}));return JSON.stringify(C,null,2)}}}}catch(u){L(`[web.search] Brave search failed, falling back: ${u}`)}let{signal:c,clear:p}=i(),m;try{m=await fetch(_x,{method:"POST",headers:{"User-Agent":$x,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:e}).toString(),signal:c})}catch(u){throw u.name==="AbortError"?new Error(s):u}finally{p()}if(m.ok){let u=await m.text(),f=Ex(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 Of,_x,$x,So,Yi=g(()=>{"use strict";l();Of=x(require("cheerio"),1);_f();Xi();k();_x="https://lite.duckduckgo.com/lite/",$x="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";So={name:Cf,displayName:kf,description:Pf,parameters:Rf,category:Sf,execute:Mx}});var Nf,Af,If,Lf,jf,Ff=g(()=>{"use strict";l();Nf="web.scrape",Af="Scrape",If="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.",Lf="network",jf={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 Ax(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,c=setTimeout(()=>a.abort(),i),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":Ox},signal:a.signal})}catch(y){throw y.name==="AbortError"?new Error(`Request timed out after ${i}ms`):y}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),u=Uf.load(m);for(let y of Nx)u(y).remove();if(n==="tables"){let y=[];return u("table").each((w,v)=>{let C=[],T=[];u(v).find("th").each((R,D)=>{T.push(u(D).text().trim())}),u(v).find("tr").each((R,D)=>{let M=T.length>0?{}:[],S=u(D).find("td");S.length>0&&(S.each(($,_)=>{let j=u(_).text().trim();T.length>0&&T[$]?M[T[$]]=j:M.push(j)}),C.push(M))}),C.length>0&&y.push({id:`Table ${w+1}`,headers:T.length>0?T: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,v=0;if(u("h1, h2, h3, h4, h5, h6").each((C,T)=>{if(u(T).text().toLowerCase().includes(y))return w=T,v=parseInt(T.tagName.charAt(1)),!1}),w){let C=u(w),T=[],R=C.next();for(;R.length>0;){let D=R.prop("tagName")?.toLowerCase();if(D&&/^h[1-6]$/.test(D)&&parseInt(D.charAt(1))<=v)break;let M=R.text().trim();M&&T.push(M),R=R.next()}T.length>0?(f=T.join(`
117
117
 
118
118
  `).replace(/\s+/g," ").trim(),f=`[Section: "${o}"]
119
119
 
@@ -121,9 +121,9 @@ ${f}`):f=`[Note: Found heading "${o}" but no content below it. Falling back to f
121
121
 
122
122
  `}else f=`[Note: Section "${o}" not found. Falling back to full page.]
123
123
 
124
- `}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 rf){let T=d(w);if(T.length>0){let S=T.text().replace(/\s+/g," ").trim();if(S.length>nf){f=S;break}}}if(f)f=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
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 qf){let v=u(w);if(v.length>0){let C=v.text().replace(/\s+/g," ").trim();if(C.length>Wf){f=C;break}}}if(f)f=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
125
125
 
126
- ${f}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let y of rf){let w=d(y);if(w.length>0){let T=w.text().replace(/\s+/g," ").trim();if(T.length>nf){f=T;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).]
126
+ ${f}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let y of qf){let w=u(y);if(w.length>0){let v=w.text().replace(/\s+/g," ").trim();if(v.length>Wf){f=v;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).]
127
127
 
128
128
  ${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
129
 
@@ -135,59 +135,169 @@ ${y}
135
135
 
136
136
  ... [Content truncated. ${f.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
137
137
 
138
- ${f}`}var sf,iT,aT,rf,nf,ao,_i=g(()=>{"use strict";c();sf=x(require("cheerio"),1);of();P();iT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",aT=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],rf=["article","main",".content","#content",'[role="main"]',"body"],nf=200;ao={name:Xu,displayName:Yu,description:Zu,parameters:tf,category:ef,execute:lT}});var af,lf,cf,pf,mf,df=g(()=>{"use strict";c();af="web.extract_links",lf="Extract Links",cf="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",pf="network",mf={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 pT(n){let e=n.url,t=n.filter,o=n.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=new AbortController,s=setTimeout(()=>r.abort(),o),i;try{i=await fetch(e,{method:"GET",headers:{"User-Agent":cT},signal:r.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=uf.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 T=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:T,url:w})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var uf,cT,lo,Ei=g(()=>{"use strict";c();uf=x(require("cheerio"),1);df();cT="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:af,displayName:lf,description:cf,parameters:mf,category:pf,execute:pT}});var ff,gf,hf,yf,bf,wf=g(()=>{"use strict";c();ff="web.map",gf="Map",hf="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.",yf="network",bf={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 dT(n){let e=n.url,t=n.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=new AbortController,r=setTimeout(()=>o.abort(),t),s;try{s=await fetch(e,{method:"GET",headers:{"User-Agent":mT},signal:o.signal})}catch(m){throw m.name==="AbortError"?new Error(`Request timed out after ${t}ms`):m}finally{clearTimeout(r)}if(!s.ok)throw new Error(`Failed to fetch ${e}: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a=Tf.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}:
138
+ ${f}`}var Uf,Ox,Nx,qf,Wf,Ro,Zi=g(()=>{"use strict";l();Uf=x(require("cheerio"),1);Ff();k();Ox="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Nx=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],qf=["article","main",".content","#content",'[role="main"]',"body"],Wf=200;Ro={name:Nf,displayName:Af,description:If,parameters:jf,category:Lf,execute:Ax}});var Gf,Bf,zf,Hf,Kf,Jf=g(()=>{"use strict";l();Gf="web.extract_links",Bf="Extract Links",zf="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Hf="network",Kf={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 Lx(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":Ix},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(),c=Vf.load(a),p=new URL(e),m=[];return c("a[href]").each((u,f)=>{let b=c(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 v=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:v,url:w})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var Vf,Ix,_o,ea=g(()=>{"use strict";l();Vf=x(require("cheerio"),1);Jf();Ix="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:Gf,displayName:Bf,description:zf,parameters:Kf,category:Hf,execute:Lx}});var Qf,Xf,Yf,Zf,eg,tg=g(()=>{"use strict";l();Qf="web.map",Xf="Map",Yf="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.",Zf="network",eg={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 Fx(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":jx},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=og.load(i),c=[];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&&c.push({level:b,text:y})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
139
139
 
140
- `;for(let m of l){let d=" ".repeat(m.level-1);p+=`${d}${"#".repeat(m.level)} ${m.text}
141
- `}return p}var Tf,mT,Qr,Di=g(()=>{"use strict";c();Tf=x(require("cheerio"),1);wf();mT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Qr={name:ff,displayName:gf,description:hf,parameters:bf,category:yf,execute:dT}});var xf,vf,Cf,Pf,Sf,kf=g(()=>{"use strict";c();xf="web.metadata",vf="Extract Metadata",Cf="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Pf="network",Sf={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 fT(n){let e=n.url,t=n.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=new AbortController,r=setTimeout(()=>o.abort(),t),s;try{s=await fetch(e,{method:"GET",headers:{"User-Agent":uT},signal:o.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${t}ms`):p}finally{clearTimeout(r)}if(!s.ok)throw new Error(`Failed to fetch ${e}: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a=Rf.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 Rf,uT,Vr,Mi=g(()=>{"use strict";c();Rf=x(require("cheerio"),1);kf();uT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Vr={name:xf,displayName:vf,description:Cf,parameters:Sf,category:Pf,execute:fT}});var $f,_f,Ef,Df,Mf,Nf=g(()=>{"use strict";c();$f="web.sitemap",_f="Extract Sitemap",Ef="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Df="network",Mf={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 Ni(n,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(n,{method:"GET",headers:{"User-Agent":gT},signal:t.signal})}catch(r){throw r.name==="AbortError"?new Error(`Request timed out after ${e}ms`):r}finally{clearTimeout(o)}}async function hT(n){let e=n.url,t=n.max_urls||100,o=n.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=e,s=!1;!e.endsWith(".xml")&&!e.endsWith(".txt")&&(r=new URL(e.endsWith("/")?"sitemap.xml":"/sitemap.xml",e).toString(),s=!0);let i;try{i=await Ni(r,o),!i.ok&&s&&(r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Ni(r,o))}catch(p){if(s)r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Ni(r,o);else throw p}if(!i||!i.ok)throw new Error(`Failed to fetch sitemap or robots.txt from ${e}`);let a=await i.text(),l=[];if(r.endsWith(".xml")||a.trim().startsWith("<")){let p=Af.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 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,r).toString()})}}}return JSON.stringify(l,null,2)}var Af,gT,Xr,Ai=g(()=>{"use strict";c();Af=x(require("cheerio"),1);Nf();gT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Xr={name:$f,displayName:_f,description:Ef,parameters:Mf,category:Df,execute:hT}});var Of,If,Lf,jf,Ff,qf=g(()=>{"use strict";c();Of="web.feed",If="Extract Feed",Lf="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",jf="network",Ff={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 Wf(){try{let n=await import("rss-parser");return new(n.default||n)}catch{throw new Error("rss-parser is not installed. Please install it using `npm install rss-parser` to use this feature.")}}var Uf=g(()=>{"use strict";c()});async function yT(n){let e=n.url,t=n.max_entries||10,o=n.timeout||3e4;if(!e)throw new Error("url is required");let r=await Wf();r.options={...r.options,timeout:o};try{let s=await r.parseURL(e),i=s.items.slice(0,t).map(a=>({title:a.title,link:a.link,published:a.pubDate||a.isoDate,summary:a.contentSnippet||a.content}));return JSON.stringify({feedTitle:s.title,feedDescription:s.description,entries:i},null,2)}catch(s){throw new Error(`Failed to parse feed from ${e}: ${s.message}`)}}var Yr,Oi=g(()=>{"use strict";c();qf();Uf();Yr={name:Of,displayName:If,description:Lf,parameters:Ff,category:jf,execute:yT}});var Gf,Bf,zf,Hf,Kf,Jf=g(()=>{"use strict";c();Gf="web.screenshot",Bf="Screenshot",zf="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",Hf="network",Kf={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 Qf(){try{let n=await import("puppeteer");return n.default||n}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var Vf=g(()=>{"use strict";c()});async function wT(n){let e=n.url,t=n.format||"html",o=n.viewport,r=n.timeout||3e4;if(!e)throw new Error("url is required");let i=await(await Qf()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(bT),await a.setViewport({width:o?.width||1280,height:o?.height||800}),await a.goto(e,{waitUntil:"networkidle2",timeout:r}),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 bT,Zr,Ii=g(()=>{"use strict";c();Jf();Vf();bT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Zr={name:Gf,displayName:Bf,description:zf,parameters:Kf,category:Hf,execute:wT}});var Xf={};te(Xf,{webExtractLinksTool:()=>lo,webFeedTool:()=>Yr,webFetchTool:()=>no,webMapTool:()=>Qr,webMetadataTool:()=>Vr,webScrapeTool:()=>ao,webScreenshotTool:()=>Zr,webSearchTool:()=>io,webSitemapTool:()=>Xr,webToolsProject:()=>Li});var Li,ji=g(()=>{"use strict";c();ki();$i();_i();Ei();Di();Mi();Ai();Oi();Ii();ki();$i();_i();Ei();Di();Mi();Ai();Oi();Ii();Li={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:[no,io,ao,lo,Qr,Vr,Xr,Yr,Zr],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Yf,Zf,eg,tg,og,rg=g(()=>{"use strict";c();Yf="coding.find_symbol",Zf="Find Symbol",eg="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",tg="coding",og={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 en(n){let e=(0,ng.extname)(n).toLowerCase();return TT[e]||"unknown"}var ng,TT,Fi=g(()=>{"use strict";c();ng=require("path"),TT={".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 Ye,ke,Le,ig,sg,qi,xT,tn,ag=g(()=>{"use strict";c();Ye=x(require("web-tree-sitter"),1),ke=x(require("fs"),1),Le=x(require("path"),1),ig=x(require("os"),1),sg=Ye.default||Ye.Parser||Ye,qi=Le.join(ig.homedir(),".toolpack-sdk","grammars"),xT=Le.resolve(__dirname,"../../grammars"),tn=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await sg.init({locateFile(e,t){return Le.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(Ye.Language||sg.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Le.resolve(__dirname,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(ke.existsSync(o))return o;let r=Le.join(xT,t);if(ke.existsSync(r))return r;let s=Le.join(qi,t);return ke.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){ke.existsSync(qi)||ke.mkdirSync(qi,{recursive:!0});let o=`https://unpkg.com/tree-sitter-wasms@latest/out/tree-sitter-${e}.wasm`,r=await fetch(o);if(!r.ok)throw new Error(`Failed to download grammar for ${e}: ${r.statusText}`);let s=await r.arrayBuffer(),i=Buffer.from(s);ke.writeFileSync(t,i)}}});var Bo,lg,cg,vT,on,pg=g(()=>{"use strict";c();Bo=x(require("web-tree-sitter"),1),lg=x(require("fs"),1),cg=x(require("crypto"),1);Fi();ag();vT=Bo.default||Bo.Parser||Bo,on=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new tn}hash(e){return cg.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:lg.readFileSync(e,"utf-8"),r=this.hash(o),s=this.treeCache.get(e),i=en(e);if(i==="unknown")throw new Error(`Unsupported file type for ${e}`);let a=await this.grammarManager.ensureGrammar(i);if(s&&s.contentHash===r)return s.lastAccessed=Date.now(),{tree:s.tree,language:s.language,grammar:a};this.parser||(await this.grammarManager.init(),this.parser=new vT),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:r,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,r]of this.treeCache.entries())r.lastAccessed<t&&(t=r.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});var mg,Wi,be,rn,dg=g(()=>{"use strict";c();mg=require("@babel/parser"),Wi=x(require("@babel/traverse"),1),be=Wi.default||Wi,rn=class{parseCode(e){return(0,mg.parse)(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,o){let r=[];try{let s=this.parseCode(e.content),i=e.filePath;be(s,{FunctionDeclaration(a){a.node.id?.name===t&&(!o||o==="function")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(a){a.node.id?.name===t&&(!o||o==="class")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(a){if(a.node.id.type==="Identifier"&&a.node.id.name===t){let l=a.parent,p=l.type==="VariableDeclaration"?l.kind:"variable";(!o||o===p||o==="variable")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(a){a.node.id.name===t&&(!o||o==="interface")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(a){a.node.id.name===t&&(!o||o==="type")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return r}async getSymbols(e,t){let o=[];try{let r=this.parseCode(e.content);be(r,{FunctionDeclaration(s){s.node.id?.name&&(!t||t==="function")&&o.push({name:s.node.id.name,kind:"function",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},ClassDeclaration(s){s.node.id?.name&&(!t||t==="class")&&o.push({name:s.node.id.name,kind:"class",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},VariableDeclarator(s){if(s.node.id.type==="Identifier"){let i=s.parent,a=i.type==="VariableDeclaration"?i.kind:"variable";(!t||t===a||t==="variable")&&o.push({name:s.node.id.name,kind:a,line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})}},TSInterfaceDeclaration(s){(!t||t==="interface")&&o.push({name:s.node.id.name,kind:"interface",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},TSTypeAliasDeclaration(s){(!t||t==="type")&&o.push({name:s.node.id.name,kind:"type",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})}})}catch(r){throw new Error(`Failed to parse file "${e.filePath}": ${r.message}`)}return o}async getImports(e){let t=[];try{let o=this.parseCode(e.content);be(o,{ImportDeclaration(r){let s=r.node.source.value,i=[],a="side-effect";for(let l of r.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:r.node.loc?.start.line||0,type:a})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return t}async findReferences(e,t,o){let r=[];try{let s=e.content,i=s.split(`
143
- `),a=this.parseCode(s);be(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]||"";r.push({file:e.filePath,line:m,column:d,context:f.trim(),isDeclaration:p})}}}})}catch{}return r}async getSymbolAtPosition(e,t,o){try{let r=this.parseCode(e.content),s=null;return be(r,{Identifier(i){let a=i.node.loc;a&&a.start.line===t&&a.start.column===o&&(s=i.node.name,i.stop())}}),s}catch{return null}}async getDefinition(e,t){try{let o=this.parseCode(e.content),r=e.filePath,s=null;return be(o,{FunctionDeclaration(i){i.node.id?.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t},i.stop())},ClassDeclaration(i){i.node.id?.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t},i.stop())},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let a=i.parent,l=a.type==="VariableDeclaration"?a.kind:"variable";s={file:r,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:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t},i.stop())},TSTypeAliasDeclaration(i){i.node.id.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t},i.stop())}}),s}catch{return null}}async getDiagnostics(e){try{return this.parseCode(e.content),[]}catch(t){return[{message:t.message,line:t.loc?.line||0,column:t.loc?.column||0,severity:"error"}]}}async getExports(e){let t=[];try{let o=this.parseCode(e.content);be(o,{ExportNamedDeclaration(r){if(r.node.declaration)if(r.node.declaration.type==="VariableDeclaration")for(let s of r.node.declaration.declarations)s.id.type==="Identifier"&&t.push({name:s.id.name,kind:"variable",line:s.loc?.start.line||0,column:s.loc?.start.column||0});else r.node.declaration.type==="FunctionDeclaration"&&r.node.declaration.id?t.push({name:r.node.declaration.id.name,kind:"function",line:r.node.declaration.loc?.start.line||0,column:r.node.declaration.loc?.start.column||0}):r.node.declaration.type==="ClassDeclaration"&&r.node.declaration.id&&t.push({name:r.node.declaration.id.name,kind:"class",line:r.node.declaration.loc?.start.line||0,column:r.node.declaration.loc?.start.column||0});else if(r.node.specifiers)for(let s of r.node.specifiers)s.exported.type==="Identifier"&&t.push({name:s.exported.name,kind:"export",line:s.loc?.start.line||0,column:s.loc?.start.column||0})},ExportDefaultDeclaration(r){let s="default",i="default";r.node.declaration.type==="ClassDeclaration"&&r.node.declaration.id?(s=r.node.declaration.id.name,i="class"):r.node.declaration.type==="FunctionDeclaration"&&r.node.declaration.id?(s=r.node.declaration.id.name,i="function"):r.node.declaration.type==="Identifier"&&(s=r.node.declaration.name,i="variable"),t.push({name:s,kind:i,line:r.node.loc?.start.line||0,column:r.node.loc?.start.column||0})}})}catch{}return t}async getOutline(e){let t=[];try{return(await this.getSymbols(e)).map(r=>({name:r.name,kind:r.kind,line:r.line,column:r.column,children:[]}))}catch{}return t}async extractFunction(e,t,o,r,s,i){let a=e.content.split(`
144
- `),l=Math.max(0,t-1),p=Math.min(a.length,r),m=a.slice(l,p).join(`
145
- `),d=`
140
+ `;for(let m of c){let u=" ".repeat(m.level-1);p+=`${u}${"#".repeat(m.level)} ${m.text}
141
+ `}return p}var og,jx,$o,ta=g(()=>{"use strict";l();og=x(require("cheerio"),1);tg();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:Qf,displayName:Xf,description:Yf,parameters:eg,category:Zf,execute:Fx}});var ng,rg,sg,ig,ag,lg=g(()=>{"use strict";l();ng="web.metadata",rg="Extract Metadata",sg="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",ig="network",ag={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 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(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=cg.load(i),c={title:a("title").text()||"",description:a('meta[name="description"]').attr("content")||a('meta[property="og:description"]').attr("content")||"",author:a('meta[name="author"]').attr("content")||"",openGraph:{},twitter:{},jsonLd:[]};return a('meta[property^="og:"]').each((p,m)=>{let u=a(m).attr("property")?.replace("og:",""),f=a(m).attr("content");u&&f&&(c.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&&(c.twitter[u]=f)}),a('script[type="application/ld+json"]').each((p,m)=>{let u=a(m).html();if(u)try{c.jsonLd.push(JSON.parse(u))}catch{}}),JSON.stringify(c,null,2)}var cg,qx,Eo,oa=g(()=>{"use strict";l();cg=x(require("cheerio"),1);lg();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:ng,displayName:rg,description:sg,parameters:ag,category:ig,execute:Wx}});var pg,mg,dg,ug,fg,gg=g(()=>{"use strict";l();pg="web.sitemap",mg="Extract Sitemap",dg="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",ug="network",fg={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 na(r,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(r,{method:"GET",headers:{"User-Agent":Ux},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function Gx(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 na(n,o),!i.ok&&s&&(n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await na(n,o))}catch(p){if(s)n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await na(n,o);else throw p}if(!i||!i.ok)throw new Error(`Failed to fetch sitemap or robots.txt from ${e}`);let a=await i.text(),c=[];if(n.endsWith(".xml")||a.trim().startsWith("<")){let p=hg.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((f,b)=>{c.length>=t||c.push({loc:p(b).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((f,b)=>{if(c.length>=t)return;let y=p(b);c.push({loc:y.children("loc").text(),lastmod:y.children("lastmod").text()||void 0,priority:y.children("priority").text()||void 0})})}else{let p=a.split(`
142
+ `);for(let m of p){if(c.length>=t)break;let u=m.trim();if(u.toLowerCase().startsWith("sitemap:"))c.push({loc:u.substring(8).trim()});else if(u.toLowerCase().startsWith("allow:")){let f=u.substring(6).trim();c.push({loc:new URL(f,n).toString()})}}}return JSON.stringify(c,null,2)}var hg,Ux,Do,ra=g(()=>{"use strict";l();hg=x(require("cheerio"),1);gg();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:pg,displayName:mg,description:dg,parameters:fg,category:ug,execute:Gx}});var yg,bg,wg,Tg,xg,vg=g(()=>{"use strict";l();yg="web.feed",bg="Extract Feed",wg="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",Tg="network",xg={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 Cg(){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 kg=g(()=>{"use strict";l()});async function Bx(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 Cg();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 Mo,sa=g(()=>{"use strict";l();vg();kg();Mo={name:yg,displayName:bg,description:wg,parameters:xg,category:Tg,execute:Bx}});var Pg,Sg,Rg,_g,$g,Eg=g(()=>{"use strict";l();Pg="web.screenshot",Sg="Screenshot",Rg="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",_g="network",$g={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 Dg(){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 Mg=g(()=>{"use strict";l()});async function Hx(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 Dg()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(zx),await a.setViewport({width:o?.width||1280,height:o?.height||800}),await a.goto(e,{waitUntil:"networkidle2",timeout:n}),t==="png"){let c=await a.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(c)?p=c.toString("base64"):p=Buffer.from(c).toString("base64"),`data:image/png;base64,${p}`}else return await a.content()}finally{await i.close()}}var zx,Oo,ia=g(()=>{"use strict";l();Eg();Mg();zx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Oo={name:Pg,displayName:Sg,description:Rg,parameters:$g,category:_g,execute:Hx}});var Og={};se(Og,{webExtractLinksTool:()=>_o,webFeedTool:()=>Mo,webFetchTool:()=>ko,webMapTool:()=>$o,webMetadataTool:()=>Eo,webScrapeTool:()=>Ro,webScreenshotTool:()=>Oo,webSearchTool:()=>So,webSitemapTool:()=>Do,webToolsProject:()=>aa});var aa,la=g(()=>{"use strict";l();Qi();Yi();Zi();ea();ta();oa();ra();sa();ia();Qi();Yi();Zi();ea();ta();oa();ra();sa();ia();aa={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,So,Ro,_o,$o,Eo,Do,Mo,Oo],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Ng,Ag,Ig,Lg,jg,Fg=g(()=>{"use strict";l();Ng="coding.find_symbol",Ag="Find Symbol",Ig="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Lg="coding",jg={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 Mr(r){let e=(0,qg.extname)(r).toLowerCase();return Kx[e]||"unknown"}var qg,Kx,ca=g(()=>{"use strict";l();qg=require("path"),Kx={".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 lt,Ne,Be,Ug,Wg,pa,Jx,Or,Gg=g(()=>{"use strict";l();lt=x(require("web-tree-sitter"),1),Ne=x(require("fs"),1),Be=x(require("path"),1),Ug=x(require("os"),1),Wg=lt.default||lt.Parser||lt,pa=Be.join(Ug.homedir(),".toolpack-sdk","grammars"),Jx=Be.resolve(__dirname,"../../grammars"),Or=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Wg.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(lt.Language||Wg.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(Ne.existsSync(o))return o;let n=Be.join(Jx,t);if(Ne.existsSync(n))return n;let s=Be.join(pa,t);return Ne.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){Ne.existsSync(pa)||Ne.mkdirSync(pa,{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 Dn,Bg,zg,Vx,Nr,Hg=g(()=>{"use strict";l();Dn=x(require("web-tree-sitter"),1),Bg=x(require("fs"),1),zg=x(require("crypto"),1);ca();Gg();Vx=Dn.default||Dn.Parser||Dn,Nr=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Or}hash(e){return zg.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:Bg.readFileSync(e,"utf-8"),n=this.hash(o),s=this.treeCache.get(e),i=Mr(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 Vx),this.parser.setLanguage(a);let c;return s?(s.tree&&s.tree.delete(),c=this.parser.parse(o)):c=this.parser.parse(o),this.treeCache.set(e,{tree:c,language:i,contentHash:n,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:c,language:i,grammar:a}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[o,n]of this.treeCache.entries())n.lastAccessed<t&&(t=n.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});var Kg,ma,_e,Ar,Jg=g(()=>{"use strict";l();Kg=require("@babel/parser"),ma=x(require("@babel/traverse"),1),_e=ma.default||ma,Ar=class{parseCode(e){return(0,Kg.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 c=a.parent,p=c.type==="VariableDeclaration"?c.kind:"variable";(!o||o===p||o==="variable")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(a){a.node.id.name===t&&(!o||o==="interface")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(a){a.node.id.name===t&&(!o||o==="type")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return n}async getSymbols(e,t){let o=[];try{let n=this.parseCode(e.content);_e(n,{FunctionDeclaration(s){s.node.id?.name&&(!t||t==="function")&&o.push({name:s.node.id.name,kind:"function",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},ClassDeclaration(s){s.node.id?.name&&(!t||t==="class")&&o.push({name:s.node.id.name,kind:"class",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},VariableDeclarator(s){if(s.node.id.type==="Identifier"){let i=s.parent,a=i.type==="VariableDeclaration"?i.kind:"variable";(!t||t===a||t==="variable")&&o.push({name:s.node.id.name,kind:a,line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})}},TSInterfaceDeclaration(s){(!t||t==="interface")&&o.push({name:s.node.id.name,kind:"interface",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},TSTypeAliasDeclaration(s){(!t||t==="type")&&o.push({name:s.node.id.name,kind:"type",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})}})}catch(n){throw new Error(`Failed to parse file "${e.filePath}": ${n.message}`)}return o}async getImports(e){let t=[];try{let o=this.parseCode(e.content);_e(o,{ImportDeclaration(n){let s=n.node.source.value,i=[],a="side-effect";for(let c of n.node.specifiers)if(c.type==="ImportDefaultSpecifier")i.push(c.local.name),a="default";else if(c.type==="ImportNamespaceSpecifier")i.push(`* as ${c.local.name}`),a="namespace";else if(c.type==="ImportSpecifier"){let p=c.imported.type==="Identifier"?c.imported.name:c.imported.value,m=c.local.name;i.push(p===m?p:`${p} as ${m}`),a="named"}t.push({source:s,imports:i,line:n.node.loc?.start.line||0,type:a})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return t}async findReferences(e,t,o){let n=[];try{let s=e.content,i=s.split(`
143
+ `),a=this.parseCode(s);_e(a,{Identifier(c){if(c.node.name===t){let p=c.isFunctionDeclaration()||c.isClassDeclaration()||c.parent.type==="VariableDeclarator"&&c.parent.id===c.node||c.parent.type==="TSInterfaceDeclaration"&&c.parent.id===c.node||c.parent.type==="TSTypeAliasDeclaration"&&c.parent.id===c.node;if(!p||o){let m=c.node.loc?.start.line||0,u=c.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,c=a.type==="VariableDeclaration"?a.kind:"variable";s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:c,name:t},i.stop()}},TSInterfaceDeclaration(i){i.node.id.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t},i.stop())},TSTypeAliasDeclaration(i){i.node.id.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t},i.stop())}}),s}catch{return null}}async getDiagnostics(e){try{return this.parseCode(e.content),[]}catch(t){return[{message:t.message,line:t.loc?.line||0,column:t.loc?.column||0,severity:"error"}]}}async getExports(e){let t=[];try{let o=this.parseCode(e.content);_e(o,{ExportNamedDeclaration(n){if(n.node.declaration)if(n.node.declaration.type==="VariableDeclaration")for(let s of n.node.declaration.declarations)s.id.type==="Identifier"&&t.push({name:s.id.name,kind:"variable",line:s.loc?.start.line||0,column:s.loc?.start.column||0});else n.node.declaration.type==="FunctionDeclaration"&&n.node.declaration.id?t.push({name:n.node.declaration.id.name,kind:"function",line:n.node.declaration.loc?.start.line||0,column:n.node.declaration.loc?.start.column||0}):n.node.declaration.type==="ClassDeclaration"&&n.node.declaration.id&&t.push({name:n.node.declaration.id.name,kind:"class",line:n.node.declaration.loc?.start.line||0,column:n.node.declaration.loc?.start.column||0});else if(n.node.specifiers)for(let s of n.node.specifiers)s.exported.type==="Identifier"&&t.push({name:s.exported.name,kind:"export",line:s.loc?.start.line||0,column:s.loc?.start.column||0})},ExportDefaultDeclaration(n){let s="default",i="default";n.node.declaration.type==="ClassDeclaration"&&n.node.declaration.id?(s=n.node.declaration.id.name,i="class"):n.node.declaration.type==="FunctionDeclaration"&&n.node.declaration.id?(s=n.node.declaration.id.name,i="function"):n.node.declaration.type==="Identifier"&&(s=n.node.declaration.name,i="variable"),t.push({name:s,kind:i,line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}})}catch{}return t}async getOutline(e){let t=[];try{return(await this.getSymbols(e)).map(n=>({name:n.name,kind:n.kind,line:n.line,column:n.column,children:[]}))}catch{}return t}async extractFunction(e,t,o,n,s,i){let a=e.content.split(`
144
+ `),c=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(c,p).join(`
145
+ `),u=`
146
146
  function ${i}() {
147
147
  ${m}
148
148
  }
149
- `,f=`${i}();`;return{newFunction:d,replacementCall:f}}async getCallHierarchy(e,t,o){try{let r=this.parseCode(e.content),s=e.filePath,i=null,a="",l=0,p=0;if(be(r,{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=[];be(r,{CallExpression(y){let w=y.node.loc;if(!w||w.start.line<l||w.end&&w.end.line>l+1e3)return;let T=!1,S=y;for(;S;){if(S.isFunction()&&S.node.type==="FunctionDeclaration"&&S.node.id?.name===a){T=!0;break}S=S.parentPath}if(!T)return;let v=y.node.callee,D="<unknown>";v.type==="Identifier"?D=v.name:v.type==="MemberExpression"&&v.property.type==="Identifier"&&(D=v.property.name),D!=="<unknown>"&&d.push({file:s,name:D,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}),be(r,{CallExpression(y){let w=y.node.callee,T=!1;if((w.type==="Identifier"&&w.name===a||w.type==="MemberExpression"&&w.property.type==="Identifier"&&w.property.name===a)&&(T=!0),T){let S="<global>",v=y;for(;v;){if(v.isFunction()){v.node.type==="FunctionDeclaration"&&v.node.id?S=v.node.id.name:v.parent.type==="VariableDeclarator"&&v.parent.id.type==="Identifier"?S=v.parent.id.name:(v.parent.type==="ClassMethod"||v.parent.type==="ObjectMethod")&&v.parent.key.type==="Identifier"&&(S=v.parent.key.name);break}v=v.parentPath}m.push({file:s,name:S,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}}}});var ug,fg=g(()=>{"use strict";c();ug={}});var nn,gg=g(()=>{"use strict";c();fg();nn=class{constructor(e){this.context=e}context;async executeQuery(e,t){let{tree:o,language:r,grammar:s}=await this.context.getTree(e.filePath,e.content),i=ug[r];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${r}`);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"),r=[];for(let s of o)if(s.name.startsWith("name.")){let i=s.name.split(".")[1];(!t||t===i)&&r.push({name:s.node.text,kind:i,line:s.node.startPosition.row+1,column:s.node.startPosition.column})}return r}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),o=t.filter(s=>s.name==="import").map(s=>s.node),r=[];for(let s of o)r.push({source:s.text,imports:[s.text],line:s.startPosition.row+1,type:"side-effect"});return r}async findReferences(e,t,o){let{captures:r}=await this.executeQuery(e,"references"),s=e.content.split(`
150
- `),i=[];for(let a of r)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:r}=await this.context.getTree(e.filePath,e.content),s=r.rootNode.descendantForPosition({row:t-1,column:o});return s&&s.type==="identifier"?s.text:null}async getDefinition(e,t){let o=await this.findSymbols(e,t);return o.length>0?o[0]:null}async getDiagnostics(e){let{tree:t}=await this.context.getTree(e.filePath,e.content),o=[];function r(s){if(s.hasError()){s.type==="ERROR"&&o.push({message:`Syntax error at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"});for(let i of s.children)r(i)}else s.isMissing&&s.isMissing()&&o.push({message:`Missing ${s.type} at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"})}return r(t.rootNode),o}async getExports(e){return[]}async getOutline(e){return(await this.getSymbols(e)).map(o=>({name:o.name,kind:o.kind,line:o.line,column:o.column,children:[]}))}async extractFunction(e,t,o,r,s,i){let a=e.content.split(`
151
- `),l=Math.max(0,t-1),p=Math.min(a.length,r),m=a.slice(l,p).join(`
152
- `),d="",f="",b=e.filePath.split(".").pop()?.toLowerCase();return b==="py"||b==="pyi"?(d=`
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="",c=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,c=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<c||w.end&&w.end.line>c+1e3)return;let v=!1,C=y;for(;C;){if(C.isFunction()&&C.node.type==="FunctionDeclaration"&&C.node.id?.name===a){v=!0;break}C=C.parentPath}if(!v)return;let T=y.node.callee,R="<unknown>";T.type==="Identifier"?R=T.name:T.type==="MemberExpression"&&T.property.type==="Identifier"&&(R=T.property.name),R!=="<unknown>"&&u.push({file:s,name:R,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}),_e(n,{CallExpression(y){let w=y.node.callee,v=!1;if((w.type==="Identifier"&&w.name===a||w.type==="MemberExpression"&&w.property.type==="Identifier"&&w.property.name===a)&&(v=!0),v){let C="<global>",T=y;for(;T;){if(T.isFunction()){T.node.type==="FunctionDeclaration"&&T.node.id?C=T.node.id.name:T.parent.type==="VariableDeclarator"&&T.parent.id.type==="Identifier"?C=T.parent.id.name:(T.parent.type==="ClassMethod"||T.parent.type==="ObjectMethod")&&T.parent.key.type==="Identifier"&&(C=T.parent.key.name);break}T=T.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:c,column:p,callers:f,callees:b}}catch{return null}}}});function ke(r,e){da[r]=e}var da,ct=g(()=>{"use strict";l();da={}});var Qx,Vg=g(()=>{"use strict";l();ct();Qx={symbols:`
150
+ (function_definition
151
+ name: (identifier) @name.function) @definition.function
152
+
153
+ (class_definition
154
+ name: (identifier) @name.class) @definition.class
155
+
156
+ (assignment
157
+ left: (identifier) @name.variable) @definition.variable
158
+ `,imports:`
159
+ (import_statement
160
+ name: (dotted_name) @name) @import
161
+
162
+ (import_from_statement
163
+ module_name: (dotted_name)? @source
164
+ name: (dotted_name) @name) @import
165
+ `,references:`
166
+ (identifier) @reference
167
+ `};ke("python",Qx)});var Xx,Qg=g(()=>{"use strict";l();ct();Xx={symbols:`
168
+ (function_declaration
169
+ name: (identifier) @name.function) @definition.function
170
+
171
+ (method_declaration
172
+ name: (field_identifier) @name.method) @definition.method
173
+
174
+ (type_spec
175
+ name: (type_identifier) @name.type) @definition.type
176
+
177
+ (var_declaration
178
+ (var_spec
179
+ name: (identifier) @name.variable)) @definition.variable
180
+ `,imports:`
181
+ (import_declaration
182
+ (import_spec
183
+ name: (package_identifier)? @name
184
+ path: (interpreted_string_literal) @source)) @import
185
+
186
+ (import_declaration
187
+ (import_spec_list
188
+ (import_spec
189
+ name: (package_identifier)? @name
190
+ path: (interpreted_string_literal) @source))) @import
191
+ `,references:`
192
+ (identifier) @reference
193
+ (field_identifier) @reference
194
+ (type_identifier) @reference
195
+ `};ke("go",Xx)});var Yx,Xg=g(()=>{"use strict";l();ct();Yx={symbols:`
196
+ (function_item
197
+ name: (identifier) @name.function) @definition.function
198
+
199
+ (struct_item
200
+ name: (type_identifier) @name.class) @definition.class
201
+
202
+ (enum_item
203
+ name: (type_identifier) @name.class) @definition.class
204
+
205
+ (trait_item
206
+ name: (type_identifier) @name.interface) @definition.interface
207
+
208
+ (let_declaration
209
+ pattern: (identifier) @name.variable) @definition.variable
210
+ `,imports:`
211
+ (use_declaration
212
+ argument: (_) @source) @import
213
+ `,references:`
214
+ (identifier) @reference
215
+ (type_identifier) @reference
216
+ (field_identifier) @reference
217
+ `};ke("rust",Yx)});var Zx,Yg=g(()=>{"use strict";l();ct();Zx={symbols:`
218
+ (method_declaration
219
+ name: (identifier) @name.method) @definition.method
220
+
221
+ (class_declaration
222
+ name: (identifier) @name.class) @definition.class
223
+
224
+ (interface_declaration
225
+ name: (identifier) @name.interface) @definition.interface
226
+
227
+ (enum_declaration
228
+ name: (identifier) @name.class) @definition.class
229
+
230
+ (variable_declarator
231
+ name: (identifier) @name.variable) @definition.variable
232
+ `,imports:`
233
+ (import_declaration
234
+ (_) @source) @import
235
+ `,references:`
236
+ (identifier) @reference
237
+ (type_identifier) @reference
238
+ `};ke("java",Zx)});var Zg,eh=g(()=>{"use strict";l();ct();Zg={symbols:`
239
+ (function_definition
240
+ declarator: (function_declarator
241
+ declarator: (identifier) @name.function)) @definition.function
242
+
243
+ (class_specifier
244
+ name: (type_identifier) @name.class) @definition.class
245
+
246
+ (struct_specifier
247
+ name: (type_identifier) @name.class) @definition.class
248
+
249
+ (declaration
250
+ declarator: (init_declarator
251
+ declarator: (identifier) @name.variable)) @definition.variable
252
+ `,imports:`
253
+ (preproc_include
254
+ path: (_) @source) @import
255
+ `,references:`
256
+ (identifier) @reference
257
+ (type_identifier) @reference
258
+ (field_identifier) @reference
259
+ `};ke("cpp",Zg);ke("c",Zg)});var Ir,th=g(()=>{"use strict";l();ct();Vg();Qg();Xg();Yg();eh();Ir=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=da[n];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${n}`);let a=i[t],c=s.query(a);return{tree:o,captures:c.captures(o.rootNode)}}async findSymbols(e,t,o){return(await this.getSymbols(e,o)).filter(s=>s.name===t).map(s=>({file:e.filePath,line:s.line,column:s.column,kind:s.kind,name:s.name}))}async getSymbols(e,t){let{captures:o}=await this.executeQuery(e,"symbols"),n=[];for(let s of o)if(s.name.startsWith("name.")){let i=s.name.split(".")[1];(!t||t===i)&&n.push({name:s.node.text,kind:i,line:s.node.startPosition.row+1,column:s.node.startPosition.column})}return n}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),o=t.filter(s=>s.name==="import").map(s=>s.node),n=[];for(let s of o)n.push({source:s.text,imports:[s.text],line:s.startPosition.row+1,type:"side-effect"});return n}async findReferences(e,t,o){let{captures:n}=await this.executeQuery(e,"references"),s=e.content.split(`
260
+ `),i=[];for(let a of n)if(a.node.text===t){let c=a.node.parent?.type.includes("definition")||a.node.parent?.type.includes("declaration");if(!c||o){let p=a.node.startPosition.row+1;i.push({file:e.filePath,line:p,column:a.node.startPosition.column,context:s[p-1].trim(),isDeclaration:!!c})}}return i}async getSymbolAtPosition(e,t,o){let{tree:n}=await this.context.getTree(e.filePath,e.content),s=n.rootNode.descendantForPosition({row:t-1,column:o});return s&&s.type==="identifier"?s.text:null}async getDefinition(e,t){let o=await this.findSymbols(e,t);return o.length>0?o[0]:null}async getDiagnostics(e){let{tree:t}=await this.context.getTree(e.filePath,e.content),o=[];function n(s){if(s.hasError()){s.type==="ERROR"&&o.push({message:`Syntax error at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"});for(let i of s.children)n(i)}else s.isMissing&&s.isMissing()&&o.push({message:`Missing ${s.type} at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"})}return n(t.rootNode),o}async getExports(e){return[]}async getOutline(e){return(await this.getSymbols(e)).map(o=>({name:o.name,kind:o.kind,line:o.line,column:o.column,children:[]}))}async extractFunction(e,t,o,n,s,i){let a=e.content.split(`
261
+ `),c=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(c,p).join(`
262
+ `),u="",f="",b=e.filePath.split(".").pop()?.toLowerCase();return b==="py"||b==="pyi"?(u=`
153
263
  def ${i}():
154
264
  ${m.split(`
155
265
  `).map(y=>" "+y).join(`
156
266
  `)}
157
- `,f=`${i}()`):b==="go"?(d=`
267
+ `,f=`${i}()`):b==="go"?(u=`
158
268
  func ${i}() {
159
269
  ${m}
160
270
  }
161
- `,f=`${i}()`):b==="rs"?(d=`
271
+ `,f=`${i}()`):b==="rs"?(u=`
162
272
  fn ${i}() {
163
273
  ${m}
164
274
  }
165
- `,f=`${i}();`):b==="sh"||b==="bash"?(d=`
275
+ `,f=`${i}();`):b==="sh"||b==="bash"?(u=`
166
276
  ${i}() {
167
277
  ${m}
168
278
  }
169
- `,f=`${i}`):(d=`
279
+ `,f=`${i}`):(u=`
170
280
  void ${i}() {
171
281
  ${m}
172
282
  }
173
- `,f=`${i}();`),{newFunction:d,replacementCall:f}}async getCallHierarchy(e,t,o){let r=await this.getSymbolAtPosition(e,t,o);if(!r)return null;let i=(await this.findReferences(e,r,!1)).map(a=>({file:a.file,name:a.context.trim()||"<anonymous>",line:a.line,column:a.column}));return{file:e.filePath,name:r,line:t,column:o,callers:i,callees:[]}}}});var sn,hg=g(()=>{"use strict";c();Fi();dg();gg();sn=class{constructor(e){this.context=e;this.babelParser=new rn,this.treeSitterParser=new nn(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(en(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 co,ln,an,yg=g(()=>{"use strict";c();co=require("fs"),ln=require("path");ie();an=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,co.readdirSync)(e,{withFileTypes:!0});for(let r of o){let s=(0,ln.join)(e,r.name);r.name==="node_modules"||r.name===".git"||r.name==="dist"||r.name==="build"||(r.isDirectory()?t.push(...await this.getAllSupportedFiles(s)):r.isFile()&&this.supportedExtensions.includes((0,ln.extname)(r.name).toLowerCase())&&t.push(s))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let o of t)await this.updateFile(o);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let o=(0,co.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let r=(0,co.readFileSync)(e,"utf-8"),s=j.getParser(e);this.removeFileFromIndex(e);let i=await s.getSymbols({filePath:e,content:r});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 CT,j,po,ie=g(()=>{"use strict";c();pg();hg();yg();CT=new on,j=new sn(CT),po=new an});async function bg(n,e,t){try{let o=(0,mo.readFileSync)(n,"utf-8");return await j.getParser(n).findSymbols({filePath:n,content:o},e,t)}catch{return[]}}async function wg(n,e,t){let o=[];try{let r=(0,mo.readdirSync)(n,{withFileTypes:!0});for(let s of r){let i=(0,cn.join)(n,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await wg(i,e,t);o.push(...a)}else if(s.isFile()&&PT.includes((0,cn.extname)(s.name))){let a=await bg(i,e,t);o.push(...a)}}}}catch{}return o}async function ST(n){let e=n.symbol,t=n.path,o=n.kind;if(h(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${o??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=(0,mo.statSync)(t),s;if(r.isDirectory())s=await wg(t,e,o);else if(r.isFile())s=await bg(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 mo,cn,PT,uo,Ui=g(()=>{"use strict";c();mo=require("fs"),cn=require("path");rg();ie();P();PT=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];uo={name:Yf,displayName:Zf,description:eg,parameters:og,category:tg,execute:ST}});var Tg,xg,vg,Cg,Pg,Sg=g(()=>{"use strict";c();Tg="coding.get_symbols",xg="Get Symbols",vg="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Cg="coding",Pg={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 kT(n){let e=n.file,t=n.kind;if(h(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=(0,kg.readFileSync)(e,"utf-8"),s=await j.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 kg,fo,Gi=g(()=>{"use strict";c();kg=require("fs");Sg();ie();P();fo={name:Tg,displayName:xg,description:vg,parameters:Pg,category:Cg,execute:kT}});var Rg,$g,_g,Eg,Dg,Mg=g(()=>{"use strict";c();Rg="coding.get_imports",$g="Get Imports",_g="List all import statements in a JavaScript/TypeScript file",Eg="coding",Dg={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function RT(n){let e=n.file;if(h(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,Ng.readFileSync)(e,"utf-8"),r=await j.getParser(e).getImports({filePath:e,content:t});return JSON.stringify({file:e,count:r.length,imports:r},null,2)}catch(t){throw new Error(`Failed to map explicit imports in file "${e}": ${t.message}`)}}var Ng,go,Bi=g(()=>{"use strict";c();Ng=require("fs");Mg();ie();P();go={name:Rg,displayName:$g,description:_g,parameters:Dg,category:Eg,execute:RT}});var Ag,Og,Ig,Lg,jg,Fg=g(()=>{"use strict";c();Ag="coding.find_references",Og="Find References",Ig="Find all references to a symbol across JavaScript/TypeScript files",Lg="coding",jg={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 qg(n,e,t){try{let o=(0,pn.readFileSync)(n,"utf-8");return await j.getParser(n).findReferences({filePath:n,content:o},e,t)}catch{return[]}}async function $T(n,e,t){let o=[];await po.buildIndex(n);let r=await po.getDefinitionFiles(e,n);for(let s of r)if(s.startsWith(n)){let i=await qg(s,e,t);o.push(...i)}return o}async function _T(n){let e=n.symbol,t=n.path,o=n.includeDeclaration===!0;if(h(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${o}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let r=(0,pn.statSync)(t),s;if(r.isDirectory())s=await $T(t,e,o);else if(r.isFile())s=await qg(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 pn,mn,zi=g(()=>{"use strict";c();pn=require("fs");Fg();ie();P();mn={name:Ag,displayName:Og,description:Ig,parameters:jg,category:Lg,execute:_T}});var Wg,Ug,Gg,Bg,zg,Hg=g(()=>{"use strict";c();Wg="coding.go_to_definition",Ug="Go To Definition",Gg="Jump to the definition of a symbol at a specific location in a file",Bg="coding",zg={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 ET(n,e,t){try{let o=(0,zo.readFileSync)(n,"utf-8");return await j.getParser(n).getSymbolAtPosition({filePath:n,content:o},e,t)}catch{return null}}async function Jg(n,e){try{let t=(0,zo.readFileSync)(n,"utf-8");return await j.getParser(n).getDefinition({filePath:n,content:t},e)}catch{return null}}async function DT(n,e){await po.buildIndex(n);let t=await po.getDefinitionFiles(e,n);for(let o of t)if(o.startsWith(n)){let r=await Jg(o,e);if(r)return r}return null}async function MT(n){let e=n.file,t=n.line,o=n.column,r=n.searchPath;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");let s=await ET(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await Jg(e,s);if(!i){let a=r||(0,Kg.dirname)(e);(0,zo.statSync)(a).isDirectory()&&(i=await DT(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 zo,Kg,dn,Hi=g(()=>{"use strict";c();zo=require("fs"),Kg=require("path");Hg();ie();dn={name:Wg,displayName:Ug,description:Gg,parameters:zg,category:Bg,execute:MT}});var Qg,Vg,Xg,Yg,Zg,eh=g(()=>{"use strict";c();Qg="coding.multi_file_edit",Vg="Multi-File Edit",Xg="Edit multiple files atomically with rollback on failure",Yg="coding",Zg={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 NT(n){let e=n.edits,t=n.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let s of e){if(!s.file)throw new Error("Each edit must have a file property");if(!s.changes||!Array.isArray(s.changes))throw new Error("Each edit must have a changes array");if(!(0,Ze.existsSync)(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],r=[];try{for(let s of e){let i=(0,Ze.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(AT(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,Ze.writeFileSync)(s.file,a,"utf-8"),r.push(s.file)}return JSON.stringify({success:!0,filesModified:r.length,files:r},null,2)}catch(s){if(t&&o.length>0){for(let i of o)try{(0,Ze.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 AT(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Ze,un,Ki=g(()=>{"use strict";c();Ze=require("fs");eh();un={name:Qg,displayName:Vg,description:Xg,parameters:Zg,category:Yg,execute:NT,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var th,oh,rh,nh,sh,ih=g(()=>{"use strict";c();th="coding.refactor_rename",oh="Refactor Rename",rh="Rename a symbol across the entire codebase intelligently",nh="coding",sh={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 LT(n,e,t,o){let r=[];try{let s=(0,ho.readFileSync)(n,"utf-8"),i=s.split(`
174
- `),a=(0,ah.parse)(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),l=[];if(OT(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}),r.push({file:n,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,ho.writeFileSync)(n,p.join(`
175
- `),"utf-8")}}catch{}return{file:n,occurrences:r.length,changes:r}}function lh(n,e,t,o){let r=[];try{let s=(0,ho.readdirSync)(n,{withFileTypes:!0});for(let i of s){let a=(0,fn.join)(n,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())r.push(...lh(a,e,t,o));else if(i.isFile()&&IT.includes((0,fn.extname)(i.name))){let l=LT(a,e,t,o);l.occurrences>0&&r.push(l)}}}}catch{}return r}async function jT(n){let e=n.symbol,t=n.newName,o=n.path,r=n.dryRun===!0;if(!e)throw new Error("symbol is required");if(!t)throw new Error("newName is required");if(!o)throw new Error("path is required");if(e===t)throw new Error("New name must be different from old name");let s=lh(o,e,t,r),i=s.reduce((l,p)=>l+p.occurrences,0),a=s.length;return JSON.stringify({success:!0,dryRun:r,oldName:e,newName:t,filesAffected:a,totalOccurrences:i,changes:s},null,2)}var ho,fn,ah,Ji,OT,IT,gn,Qi=g(()=>{"use strict";c();ho=require("fs"),fn=require("path"),ah=require("@babel/parser"),Ji=x(require("@babel/traverse"),1);ih();OT=Ji.default||Ji,IT=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];gn={name:th,displayName:oh,description:rh,parameters:sh,category:nh,execute:jT,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var ch,ph,mh,dh,uh,fh=g(()=>{"use strict";c();ch="coding.get_outline",ph="Get File Outline",mh="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",dh="coding",uh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function FT(n){let e=n.file;if(h(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,hn.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,hn.readFileSync)(e,"utf-8"),o=j.getParser(e);if(!o.getOutline)return JSON.stringify({file:e,error:"Outline extraction is not specifically implemented for this language yet."});let r=await o.getOutline({filePath:e,content:t});return JSON.stringify({file:e,outline:r},null,2)}catch(t){throw new Error(`Failed to safely extract outline from file "${e}": ${t.message}`)}}var hn,yn,Vi=g(()=>{"use strict";c();hn=require("fs");fh();ie();P();yn={name:ch,displayName:ph,description:mh,parameters:uh,category:dh,execute:FT}});var gh,hh,yh,bh,wh,Th=g(()=>{"use strict";c();gh="coding.get_diagnostics",hh="Get File Diagnostics",yh="Gets syntax errors and warnings for a file utilizing AST parsing.",bh="coding",wh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function qT(n){let e=n.file;if(!e)throw new Error("file is required");try{if(!(0,bn.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,bn.readFileSync)(e,"utf-8"),o=j.getParser(e);if(!o.getDiagnostics)return JSON.stringify({file:e,error:"Diagnostics extraction is not specifically implemented for this language yet."});let r=await o.getDiagnostics({filePath:e,content:t});return JSON.stringify({file:e,diagnostics:r},null,2)}catch(t){throw new Error(`Failed to get diagnostics from file "${e}": ${t.message}`)}}var bn,wn,Xi=g(()=>{"use strict";c();bn=require("fs");Th();ie();wn={name:gh,displayName:hh,description:yh,parameters:wh,category:bh,execute:qT}});var xh,vh,Ch,Ph,Sh,kh=g(()=>{"use strict";c();xh="coding.get_exports",vh="Get File Exports",Ch="Lists all symbols exported by a file.",Ph="coding",Sh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function WT(n){let e=n.file;if(h(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Tn.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Tn.readFileSync)(e,"utf-8"),o=j.getParser(e);if(!o.getExports)return JSON.stringify({file:e,error:"Exports extraction is not specifically implemented for this language yet."});let r=await o.getExports({filePath:e,content:t});return JSON.stringify({file:e,exports:r},null,2)}catch(t){throw new Error(`Failed to extract exports from file "${e}": ${t.message}`)}}var Tn,xn,Yi=g(()=>{"use strict";c();Tn=require("fs");kh();ie();P();xn={name:xh,displayName:vh,description:Ch,parameters:Sh,category:Ph,execute:WT}});var Rh,$h,_h,Eh,Dh,Mh=g(()=>{"use strict";c();Rh="coding.extract_function",$h="Extract Function",_h="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Eh="coding",Dh={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 UT(n){let e=n.file,t=n.startLine,o=n.startColumn,r=n.endLine,s=n.endColumn,i=n.newFunctionName;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("startLine is required");if(o===void 0)throw new Error("startColumn is required");if(r===void 0)throw new Error("endLine is required");if(s===void 0)throw new Error("endColumn is required");if(!i)throw new Error("newFunctionName is required");try{if(!(0,vn.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=(0,vn.readFileSync)(e,"utf-8"),l=j.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,r,s,i);return JSON.stringify({file:e,result:p},null,2)}catch(a){throw new Error(`Failed to extract function from file "${e}": ${a.message}`)}}var vn,Cn,Zi=g(()=>{"use strict";c();vn=require("fs");Mh();ie();Cn={name:Rh,displayName:$h,description:_h,parameters:Dh,category:Eh,execute:UT}});var Nh,Ah,Oh,Ih,Lh,jh=g(()=>{"use strict";c();Nh="coding.get_call_hierarchy",Ah="Get Call Hierarchy",Oh="Shows callers and callees of a specific function or method.",Ih="coding",Lh={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 GT(n){let e=n.file,t=n.line,o=n.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");try{if(!(0,Pn.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let r=(0,Pn.readFileSync)(e,"utf-8"),s=j.getParser(e);if(!s.getCallHierarchy)return JSON.stringify({file:e,error:"Call hierarchy is not specifically implemented for this language yet."});let i=await s.getCallHierarchy({filePath:e,content:r},t,o);return JSON.stringify({file:e,hierarchy:i},null,2)}catch(r){throw new Error(`Failed to get call hierarchy from file "${e}": ${r.message}`)}}var Pn,Sn,ea=g(()=>{"use strict";c();Pn=require("fs");jh();ie();Sn={name:Nh,displayName:Ah,description:Oh,parameters:Lh,category:Ih,execute:GT}});var Fh={};te(Fh,{codingExtractFunctionTool:()=>Cn,codingFindReferencesTool:()=>mn,codingFindSymbolTool:()=>uo,codingGetCallHierarchyTool:()=>Sn,codingGetDiagnosticsTool:()=>wn,codingGetExportsTool:()=>xn,codingGetImportsTool:()=>go,codingGetOutlineTool:()=>yn,codingGetSymbolsTool:()=>fo,codingGoToDefinitionTool:()=>dn,codingMultiFileEditTool:()=>un,codingRefactorRenameTool:()=>gn,codingToolsProject:()=>ta});var ta,oa=g(()=>{"use strict";c();Ui();Gi();Bi();zi();Hi();Ki();Qi();Vi();Xi();Yi();Zi();ea();Ui();Gi();Bi();zi();Hi();Ki();Qi();Vi();Xi();Yi();Zi();ea();ta={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:[uo,fo,go,mn,dn,yn,wn,xn,Cn,Sn,un,gn],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var qh,Wh=g(()=>{"use strict";c();qh={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function z(n){let e={baseDir:n||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,Uh.simpleGit)(e)}var Uh,we=g(()=>{"use strict";c();Uh=require("simple-git")});var Ho,Gh=g(()=>{"use strict";c();Wh();we();Ho={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:qh,execute:async n=>{let e=n.path;try{let o=await z().status(e?[e]:[]);if(o.isClean())return"Working tree clean";let r=[];return r.push(`Branch: ${o.current}`),o.tracking&&r.push(`Tracking: ${o.tracking}`),o.ahead>0&&r.push(`Ahead: ${o.ahead}`),o.behind>0&&r.push(`Behind: ${o.behind}`),r.push("---"),o.conflicted.length>0&&r.push(`Conflicted: ${o.conflicted.join(", ")}`),o.created.length>0&&r.push(`Created: ${o.created.join(", ")}`),o.deleted.length>0&&r.push(`Deleted: ${o.deleted.join(", ")}`),o.modified.length>0&&r.push(`Modified: ${o.modified.join(", ")}`),o.renamed.length>0&&r.push(`Renamed: ${o.renamed.map(s=>`${s.from} -> ${s.to}`).join(", ")}`),o.staged.length>0&&r.push(`Staged: ${o.staged.join(", ")}`),o.not_added.length>0&&r.push(`Untracked: ${o.not_added.join(", ")}`),r.join(`
176
- `)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var Bh,zh=g(()=>{"use strict";c();Bh={type:"object",properties:{path:{type:"string",description:"Optional path to get the diff for. If omitted, gets the diff for the entire repository."},staged:{type:"boolean",description:"If true, gets the diff of staged changes instead of unstaged changes.",default:!1}}}});var Ko,Hh=g(()=>{"use strict";c();zh();we();Ko={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:Bh,execute:async n=>{let e=n.path,t=n.staged;try{let o=z(),r=[];t&&r.push("--cached"),e&&r.push("--",e);let s=await o.diff(r);return s||"No changes found."}catch(o){return`Error getting git diff: ${o instanceof Error?o.message:String(o)}`}}}});var Kh,Jh=g(()=>{"use strict";c();Kh={type:"object",properties:{maxCount:{type:"number",description:"Maximum number of commits to return. Defaults to 10 to prevent large outputs.",default:10},path:{type:"string",description:"Optional path to get the log for specific file or directory."}}}});var Jo,Qh=g(()=>{"use strict";c();Jh();we();Jo={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:Kh,execute:async n=>{let e=n.maxCount||10,t=n.path;try{let o=z(),r={maxCount:e};t&&(r.file=t);let s=await o.log(r);return s.all.length===0?"No commits found.":s.all.map(i=>`Commit: ${i.hash}
177
- Author: ${i.author_name} <${i.author_email}>
178
- Date: ${i.date}
179
- Message: ${i.message}
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 Lr,oh=g(()=>{"use strict";l();ca();Jg();th();Lr=class{constructor(e){this.context=e;this.babelParser=new Ar,this.treeSitterParser=new Ir(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Mr(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 No,Fr,jr,nh=g(()=>{"use strict";l();No=require("fs"),Fr=require("path");ue();jr=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,No.readdirSync)(e,{withFileTypes:!0});for(let n of o){let s=(0,Fr.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,Fr.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,No.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=(0,No.readFileSync)(e,"utf-8"),s=W.getParser(e);this.removeFileFromIndex(e);let i=await s.getSymbols({filePath:e,content:n});for(let a of i){let c=this.data.symbolLocations.get(a.name);c?c.add(e):this.data.symbolLocations.set(a.name,new Set([e]))}this.fileMtimes.set(e,o)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,o]of this.data.symbolLocations.entries())o.delete(e),o.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let o=this.data.symbolLocations.get(e);return o?Array.from(o):[]}}});var ev,W,Ao,ue=g(()=>{"use strict";l();Hg();oh();nh();ev=new Nr,W=new Lr(ev),Ao=new jr});async function rh(r,e,t){try{let o=(0,Io.readFileSync)(r,"utf-8");return await W.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function sh(r,e,t){let o=[];try{let n=(0,Io.readdirSync)(r,{withFileTypes:!0});for(let s of n){let i=(0,qr.join)(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await sh(i,e,t);o.push(...a)}else if(s.isFile()&&tv.includes((0,qr.extname)(s.name))){let a=await rh(i,e,t);o.push(...a)}}}}catch{}return o}async function ov(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,Io.statSync)(t),s;if(n.isDirectory())s=await sh(t,e,o);else if(n.isFile())s=await rh(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 Io,qr,tv,Lo,ua=g(()=>{"use strict";l();Io=require("fs"),qr=require("path");Fg();ue();k();tv=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Lo={name:Ng,displayName:Ag,description:Ig,parameters:jg,category:Lg,execute:ov}});var ih,ah,lh,ch,ph,mh=g(()=>{"use strict";l();ih="coding.get_symbols",ah="Get Symbols",lh="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",ch="coding",ph={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 nv(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,dh.readFileSync)(e,"utf-8"),s=await W.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 dh,jo,fa=g(()=>{"use strict";l();dh=require("fs");mh();ue();k();jo={name:ih,displayName:ah,description:lh,parameters:ph,category:ch,execute:nv}});var uh,fh,gh,hh,yh,bh=g(()=>{"use strict";l();uh="coding.get_imports",fh="Get Imports",gh="List all import statements in a JavaScript/TypeScript file",hh="coding",yh={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function rv(r){let e=r.file;if(h(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,wh.readFileSync)(e,"utf-8"),n=await W.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 wh,Fo,ga=g(()=>{"use strict";l();wh=require("fs");bh();ue();k();Fo={name:uh,displayName:fh,description:gh,parameters:yh,category:hh,execute:rv}});var Th,xh,vh,Ch,kh,Ph=g(()=>{"use strict";l();Th="coding.find_references",xh="Find References",vh="Find all references to a symbol across JavaScript/TypeScript files",Ch="coding",kh={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 Sh(r,e,t){try{let o=(0,Wr.readFileSync)(r,"utf-8");return await W.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function sv(r,e,t){let o=[];await Ao.buildIndex(r);let n=await Ao.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await Sh(s,e,t);o.push(...i)}return o}async function iv(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,Wr.statSync)(t),s;if(n.isDirectory())s=await sv(t,e,o);else if(n.isFile())s=await Sh(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 Wr,qo,ha=g(()=>{"use strict";l();Wr=require("fs");Ph();ue();k();qo={name:Th,displayName:xh,description:vh,parameters:kh,category:Ch,execute:iv}});var Rh,_h,$h,Eh,Dh,Mh=g(()=>{"use strict";l();Rh="coding.go_to_definition",_h="Go To Definition",$h="Jump to the definition of a symbol at a specific location in a file",Eh="coding",Dh={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 av(r,e,t){try{let o=(0,Mn.readFileSync)(r,"utf-8");return await W.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function Nh(r,e){try{let t=(0,Mn.readFileSync)(r,"utf-8");return await W.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function lv(r,e){await Ao.buildIndex(r);let t=await Ao.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await Nh(o,e);if(n)return n}return null}async function cv(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 av(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await Nh(e,s);if(!i){let a=n||(0,Oh.dirname)(e);(0,Mn.statSync)(a).isDirectory()&&(i=await lv(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 Mn,Oh,Wo,ya=g(()=>{"use strict";l();Mn=require("fs"),Oh=require("path");Mh();ue();Wo={name:Rh,displayName:_h,description:$h,parameters:Dh,category:Eh,execute:cv}});var Ah,Ih,Lh,jh,Fh,qh=g(()=>{"use strict";l();Ah="coding.multi_file_edit",Ih="Multi-File Edit",Lh="Edit multiple files atomically with rollback on failure",jh="coding",Fh={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 pv(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,pt.existsSync)(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=(0,pt.readFileSync)(s.file,"utf-8");t&&o.push({file:s.file,content:i});let a=i;for(let c of s.changes){if(!c.oldText)throw new Error("Each change must have oldText property");if(c.newText===void 0)throw new Error("Each change must have newText property");let p=(a.match(new RegExp(mv(c.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${s.file}: "${c.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${s.file}: "${c.oldText.substring(0,50)}..." appears ${p} times`);a=a.replace(c.oldText,c.newText)}(0,pt.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,pt.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 mv(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var pt,Uo,ba=g(()=>{"use strict";l();pt=require("fs");qh();Uo={name:Ah,displayName:Ih,description:Lh,parameters:Fh,category:jh,execute:pv,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var Wh,Uh,Gh,Bh,zh,Hh=g(()=>{"use strict";l();Wh="coding.refactor_rename",Uh="Refactor Rename",Gh="Rename a symbol across the entire codebase intelligently",Bh="coding",zh={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 fv(r,e,t,o){let n=[];try{let s=(0,Go.readFileSync)(r,"utf-8"),i=s.split(`
284
+ `),a=(0,Kh.parse)(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(dv(a,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,u=p.node.loc?.start.column||0;c.push({line:m,column:u,length:e.length}),n.push({file:r,line:m,column:u,oldName:e,newName:t})}}}),!o&&c.length>0){c.sort((m,u)=>m.line!==u.line?u.line-m.line:u.column-m.column);let p=[...i];for(let m of c){let u=m.line-1;if(u>=0&&u<p.length){let f=p[u],b=f.substring(0,m.column),y=f.substring(m.column+m.length);p[u]=b+t+y}}(0,Go.writeFileSync)(r,p.join(`
285
+ `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function Jh(r,e,t,o){let n=[];try{let s=(0,Go.readdirSync)(r,{withFileTypes:!0});for(let i of s){let a=(0,Ur.join)(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...Jh(a,e,t,o));else if(i.isFile()&&uv.includes((0,Ur.extname)(i.name))){let c=fv(a,e,t,o);c.occurrences>0&&n.push(c)}}}}catch{}return n}async function gv(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=Jh(o,e,t,n),i=s.reduce((c,p)=>c+p.occurrences,0),a=s.length;return JSON.stringify({success:!0,dryRun:n,oldName:e,newName:t,filesAffected:a,totalOccurrences:i,changes:s},null,2)}var Go,Ur,Kh,wa,dv,uv,Bo,Ta=g(()=>{"use strict";l();Go=require("fs"),Ur=require("path"),Kh=require("@babel/parser"),wa=x(require("@babel/traverse"),1);Hh();dv=wa.default||wa,uv=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Bo={name:Wh,displayName:Uh,description:Gh,parameters:zh,category:Bh,execute:gv,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var Vh,Qh,Xh,Yh,Zh,ey=g(()=>{"use strict";l();Vh="coding.get_outline",Qh="Get File Outline",Xh="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",Yh="coding",Zh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function hv(r){let e=r.file;if(h(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,Gr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,Gr.readFileSync)(e,"utf-8"),o=W.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 Gr,zo,xa=g(()=>{"use strict";l();Gr=require("fs");ey();ue();k();zo={name:Vh,displayName:Qh,description:Xh,parameters:Zh,category:Yh,execute:hv}});var ty,oy,ny,ry,sy,iy=g(()=>{"use strict";l();ty="coding.get_diagnostics",oy="Get File Diagnostics",ny="Gets syntax errors and warnings for a file utilizing AST parsing.",ry="coding",sy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function yv(r){let e=r.file;if(!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=W.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 Br,Ho,va=g(()=>{"use strict";l();Br=require("fs");iy();ue();Ho={name:ty,displayName:oy,description:ny,parameters:sy,category:ry,execute:yv}});var ay,ly,cy,py,my,dy=g(()=>{"use strict";l();ay="coding.get_exports",ly="Get File Exports",cy="Lists all symbols exported by a file.",py="coding",my={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function bv(r){let e=r.file;if(h(`[coding.get-exports] execute file="${e}"`),!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=W.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 zr,Ko,Ca=g(()=>{"use strict";l();zr=require("fs");dy();ue();k();Ko={name:ay,displayName:ly,description:cy,parameters:my,category:py,execute:bv}});var uy,fy,gy,hy,yy,by=g(()=>{"use strict";l();uy="coding.extract_function",fy="Extract Function",gy="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",hy="coding",yy={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 wv(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,Hr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=(0,Hr.readFileSync)(e,"utf-8"),c=W.getParser(e);if(!c.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await c.extractFunction({filePath:e,content:a},t,o,n,s,i);return JSON.stringify({file:e,result:p},null,2)}catch(a){throw new Error(`Failed to extract function from file "${e}": ${a.message}`)}}var Hr,Jo,ka=g(()=>{"use strict";l();Hr=require("fs");by();ue();Jo={name:uy,displayName:fy,description:gy,parameters:yy,category:hy,execute:wv}});var wy,Ty,xy,vy,Cy,ky=g(()=>{"use strict";l();wy="coding.get_call_hierarchy",Ty="Get Call Hierarchy",xy="Shows callers and callees of a specific function or method.",vy="coding",Cy={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 Tv(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,Kr.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=(0,Kr.readFileSync)(e,"utf-8"),s=W.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 Kr,Vo,Pa=g(()=>{"use strict";l();Kr=require("fs");ky();ue();Vo={name:wy,displayName:Ty,description:xy,parameters:Cy,category:vy,execute:Tv}});var Py={};se(Py,{codingExtractFunctionTool:()=>Jo,codingFindReferencesTool:()=>qo,codingFindSymbolTool:()=>Lo,codingGetCallHierarchyTool:()=>Vo,codingGetDiagnosticsTool:()=>Ho,codingGetExportsTool:()=>Ko,codingGetImportsTool:()=>Fo,codingGetOutlineTool:()=>zo,codingGetSymbolsTool:()=>jo,codingGoToDefinitionTool:()=>Wo,codingMultiFileEditTool:()=>Uo,codingRefactorRenameTool:()=>Bo,codingToolsProject:()=>Sa});var Sa,Ra=g(()=>{"use strict";l();ua();fa();ga();ha();ya();ba();Ta();xa();va();Ca();ka();Pa();ua();fa();ga();ha();ya();ba();Ta();xa();va();Ca();ka();Pa();Sa={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:[Lo,jo,Fo,qo,Wo,zo,Ho,Ko,Jo,Vo,Uo,Bo],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var Sy,Ry=g(()=>{"use strict";l();Sy={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function U(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,_y.simpleGit)(e)}var _y,Pe=g(()=>{"use strict";l();_y=require("simple-git")});var On,$y=g(()=>{"use strict";l();Ry();Pe();On={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:Sy,execute:async r=>{let e=r.path;try{let o=await U().status(e?[e]:[]);if(o.isClean())return"Working tree clean";let n=[];return n.push(`Branch: ${o.current}`),o.tracking&&n.push(`Tracking: ${o.tracking}`),o.ahead>0&&n.push(`Ahead: ${o.ahead}`),o.behind>0&&n.push(`Behind: ${o.behind}`),n.push("---"),o.conflicted.length>0&&n.push(`Conflicted: ${o.conflicted.join(", ")}`),o.created.length>0&&n.push(`Created: ${o.created.join(", ")}`),o.deleted.length>0&&n.push(`Deleted: ${o.deleted.join(", ")}`),o.modified.length>0&&n.push(`Modified: ${o.modified.join(", ")}`),o.renamed.length>0&&n.push(`Renamed: ${o.renamed.map(s=>`${s.from} -> ${s.to}`).join(", ")}`),o.staged.length>0&&n.push(`Staged: ${o.staged.join(", ")}`),o.not_added.length>0&&n.push(`Untracked: ${o.not_added.join(", ")}`),n.join(`
286
+ `)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var Ey,Dy=g(()=>{"use strict";l();Ey={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 Nn,My=g(()=>{"use strict";l();Dy();Pe();Nn={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:Ey,execute:async r=>{let e=r.path,t=r.base,o=r.head,n=r.staged,s=r.cloneDir;try{let i=U(s),a=[];if(t||o){if(!t||!o)return"Error getting git diff: both base and head are required when comparing revisions.";a.push(`${t}...${o}`)}n&&a.push("--cached"),e&&a.push("--",e);let c=await i.diff(a);return c||"No changes found."}catch(i){return`Error getting git diff: ${i instanceof Error?i.message:String(i)}`}}}});var Oy,Ny=g(()=>{"use strict";l();Oy={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 An,Ay=g(()=>{"use strict";l();Ny();Pe();An={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:Oy,execute:async r=>{let e=r.maxCount||10,t=r.path,o=r.cloneDir;try{let n=U(o),s={maxCount:e};t&&(s.file=t);let i=await n.log(s);return i.all.length===0?"No commits found.":i.all.map(a=>`Commit: ${a.hash}
287
+ Author: ${a.author_name} <${a.author_email}>
288
+ Date: ${a.date}
289
+ Message: ${a.message}
180
290
  `).join(`---
181
- `)}catch(o){return`Error getting git log: ${o instanceof Error?o.message:String(o)}`}}}});var Vh,Xh=g(()=>{"use strict";c();Vh={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Qo,Yh=g(()=>{"use strict";c();Xh();we();Qo={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:Vh,execute:async n=>{let e=n.path;try{return await z().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var Zh,ey=g(()=>{"use strict";c();Zh={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Vo,ty=g(()=>{"use strict";c();ey();we();Vo={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Zh,execute:async n=>{let e=n.message;try{let o=await z().commit(e);return o.commit?`Successfully committed changes.
291
+ `)}catch(n){return`Error getting git log: ${n instanceof Error?n.message:String(n)}`}}}});var Iy,Ly=g(()=>{"use strict";l();Iy={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var In,jy=g(()=>{"use strict";l();Ly();Pe();In={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:Iy,execute:async r=>{let e=r.path;try{return await U().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var Fy,qy=g(()=>{"use strict";l();Fy={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Ln,Wy=g(()=>{"use strict";l();qy();Pe();Ln={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Fy,execute:async r=>{let e=r.message;try{let o=await U().commit(e);return o.commit?`Successfully committed changes.
182
292
  Commit: ${o.commit}
183
293
  Branch: ${o.branch}
184
- 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 oy,ry=g(()=>{"use strict";c();oy={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."}},required:["path"]}});var Xo,ny=g(()=>{"use strict";c();ry();we();Xo={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:oy,execute:async n=>{let e=n.path;try{return await z().raw(["blame",e])}catch(t){return`Error running git blame: ${t instanceof Error?t.message:String(t)}`}}}});var sy,iy=g(()=>{"use strict";c();sy={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Yo,ay=g(()=>{"use strict";c();iy();we();Yo={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:sy,execute:async n=>{let e=n.remote;try{let t=z(),o=e?["-a"]:[],r=await t.branch(o);return`Current Branch: ${r.current}
294
+ Summary: ${o.summary.changes} changes, ${o.summary.insertions} insertions, ${o.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will create a permanent commit in the repository history.",showArgs:["message"]}}});var Uy,Gy=g(()=>{"use strict";l();Uy={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."},sha:{type:"string",description:"Optional commit SHA or ref to blame at. If omitted, blames the current checkout."},cloneDir:{type:"string",description:"Optional local repository directory, typically the cloneDir returned by git.clone. When provided, this tool runs in that repository instead of the current working directory."}},required:["path"]}});var jn,By=g(()=>{"use strict";l();Gy();Pe();jn={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:Uy,execute:async r=>{let e=r.path,t=r.sha,o=r.cloneDir;try{let n=U(o),s=["blame"];return t&&s.push(t),s.push("--",e),await n.raw(s)}catch(n){return`Error running git blame: ${n instanceof Error?n.message:String(n)}`}}}});var zy,Hy=g(()=>{"use strict";l();zy={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Fn,Ky=g(()=>{"use strict";l();Hy();Pe();Fn={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:zy,execute:async r=>{let e=r.remote;try{let t=U(),o=e?["-a"]:[],n=await t.branch(o);return`Current Branch: ${n.current}
185
295
 
186
296
  Branches:
187
- ${r.all.join(`
188
- `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var ly,cy=g(()=>{"use strict";c();ly={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 Zo,py=g(()=>{"use strict";c();cy();we();Zo={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:ly,execute:async n=>{let e=n.name,t=n.checkout,o=n.startPoint;try{let r=z();return t?(o?await r.checkoutBranch(e,o):await r.checkoutLocalBranch(e),`Successfully created and switched to branch: ${e}`):(o?await r.branch([e,o]):await r.branch([e]),`Successfully created branch: ${e}`)}catch(r){return`Error creating branch: ${r instanceof Error?r.message:String(r)}`}}}});var my,dy=g(()=>{"use strict";c();my={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var er,uy=g(()=>{"use strict";c();dy();we();er={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:my,execute:async n=>{let e=n.branch;try{return await z().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 fy={};te(fy,{gitAddTool:()=>Qo,gitBlameTool:()=>Xo,gitBranchCreateTool:()=>Zo,gitBranchListTool:()=>Yo,gitCheckoutTool:()=>er,gitCommitTool:()=>Vo,gitDiffTool:()=>Ko,gitLogTool:()=>Jo,gitStatusTool:()=>Ho,gitToolsProject:()=>ra});var ra,na=g(()=>{"use strict";c();Gh();Hh();Qh();Yh();ty();ny();ay();py();uy();ra={manifest:{key:"git",name:"git-tools",displayName:"Git Version Control",version:"1.0.0",description:"Git operations for reading repository state, checking diffs, creating commits, and managing branches.",author:"Sajeer",tools:["git.status","git.diff","git.log","git.add","git.commit","git.blame","git.branch_list","git.branch_create","git.checkout"],category:"version-control"},tools:[Ho,Ko,Jo,Qo,Vo,Xo,Yo,Zo,er],dependencies:{"simple-git":"^3.27.0"}}});var gy,hy=g(()=>{"use strict";c();gy={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 yy,tr,by=g(()=>{"use strict";c();hy();yy=x(require("diff"),1);P();tr={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:gy,execute:async n=>{let e=n.oldContent,t=n.newContent,o=n.fileName||"file",r=n.contextLines??4;h(`[diff.create] execute fileName="${o}" contextLines=${r}`);try{return yy.createPatch(o,e,t,"","",{context:r})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var wy,Ty=g(()=>{"use strict";c();wy={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 xy,sa,or,vy=g(()=>{"use strict";c();Ty();xy=x(require("diff"),1),sa=require("fs");P();or={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:wy,execute:async n=>{let e=n.path,t=n.patch;h(`[diff.apply] execute path="${e}"`);try{let o=await sa.promises.readFile(e,"utf8"),r=xy.applyPatch(o,t);return r===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await sa.promises.writeFile(e,r,"utf8"),`Successfully applied patch to ${e}`)}catch(o){return`Error applying patch: ${o instanceof Error?o.message:String(o)}`}},confirmation:{level:"high",reason:"This will apply a patch to files, which may corrupt them if the patch doesn't match.",showArgs:["path"]}}});var Cy,Py=g(()=>{"use strict";c();Cy={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 Sy,ky,rr,Ry=g(()=>{"use strict";c();Py();Sy=x(require("diff"),1),ky=require("fs"),rr={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:Cy,execute:async n=>{let e=n.path,t=n.patch;try{let o=await ky.promises.readFile(e,"utf8"),r=Sy.applyPatch(o,t);return r===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
297
+ ${n.all.join(`
298
+ `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Jy,Vy=g(()=>{"use strict";l();Jy={type:"object",properties:{name:{type:"string",description:"Name of the new branch."},checkout:{type:"boolean",description:"Whether to checkout the new branch after creating it.",default:!1},startPoint:{type:"string",description:"Optional start point (commit hash or branch name) for the new branch."}},required:["name"]}});var qn,Qy=g(()=>{"use strict";l();Vy();Pe();qn={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Jy,execute:async r=>{let e=r.name,t=r.checkout,o=r.startPoint;try{let n=U();return t?(o?await n.checkoutBranch(e,o):await n.checkoutLocalBranch(e),`Successfully created and switched to branch: ${e}`):(o?await n.branch([e,o]):await n.branch([e]),`Successfully created branch: ${e}`)}catch(n){return`Error creating branch: ${n instanceof Error?n.message:String(n)}`}}}});var Xy,Yy=g(()=>{"use strict";l();Xy={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Wn,Zy=g(()=>{"use strict";l();Yy();Pe();Wn={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Xy,execute:async r=>{let e=r.branch;try{return await U().checkout(e),`Successfully checked out: ${e}`}catch(t){return`Error checking out branch: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will switch branches, potentially losing uncommitted changes.",showArgs:["branch"]}}});var eb,tb=g(()=>{"use strict";l();eb={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 Cv(r){for(;Jr.has(r);)await Jr.get(r);let e,t=new Promise(o=>{e=o});return Jr.set(r,t),()=>{Jr.delete(r),e()}}async function ob(r){let e=0,t=await ae.readdir(r,{withFileTypes:!0});for(let o of t){let n=Vr.join(r,o.name);if(o.isDirectory())e+=await ob(n);else if(o.isFile()){let s=await ae.stat(n);e+=s.size}}return e}async function kv(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 ae.rm(o.cloneDir,{recursive:!0,force:!0}),ze=Math.max(0,ze-o.sizeBytes),He.delete(n)}catch{break}}}async function Pv(r,e,t,o,n){let i=`https://x-access-token:${await G(r)}@github.com/${r}.git`,a=r.replace("/","_"),c=Vr.resolve(n,a),p=U(n),m=He.get(r);if(m)try{if(await ae.access(c),m.sha===e)return m.lastAccessedAt=Date.now(),c;await ae.rm(c,{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 ae.access(c),await ae.rm(c,{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=U(c);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 ob(c);return ze+=b,He.set(r,{cloneDir:c,repo:r,sha:e,sizeBytes:b,lastAccessedAt:Date.now()}),c}catch(f){try{await ae.rm(c,{recursive:!0,force:!0})}catch{}throw f}}function Sv(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}var ae,Vr,xv,vv,He,Jr,ze,Un,nb=g(()=>{"use strict";l();tb();Pe();Ce();ae=x(require("fs/promises"),1),Vr=x(require("path"),1),xv=".toolpack/clones",vv=5e9,He=new Map,Jr=new Map,ze=0;Un={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:eb,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??xv,i=parseInt(process.env.SENTINEL_CLONE_MAX_BYTES??"0",10)||vv;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 ae.mkdir(s,{recursive:!0});let c=await Cv(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 kv(1e8,i);let m=await Pv(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: ${Sv(p)}`}finally{c()}}}});var rb={};se(rb,{gitAddTool:()=>In,gitBlameTool:()=>jn,gitBranchCreateTool:()=>qn,gitBranchListTool:()=>Fn,gitCheckoutTool:()=>Wn,gitCloneTool:()=>Un,gitCommitTool:()=>Ln,gitDiffTool:()=>Nn,gitLogTool:()=>An,gitStatusTool:()=>On,gitToolsProject:()=>_a});var _a,$a=g(()=>{"use strict";l();$y();My();Ay();jy();Wy();By();Ky();Qy();Zy();nb();_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:[On,Nn,An,In,Ln,jn,Fn,qn,Wn,Un],dependencies:{"simple-git":"^3.27.0"}}});var sb,ib=g(()=>{"use strict";l();sb={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 ab,Gn,lb=g(()=>{"use strict";l();ib();ab=x(require("diff"),1);k();Gn={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:sb,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 ab.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var cb,pb=g(()=>{"use strict";l();cb={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 mb,Ea,Bn,db=g(()=>{"use strict";l();pb();mb=x(require("diff"),1),Ea=require("fs");k();Bn={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:cb,execute:async r=>{let e=r.path,t=r.patch;h(`[diff.apply] execute path="${e}"`);try{let o=await Ea.promises.readFile(e,"utf8"),n=mb.applyPatch(o,t);return n===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await Ea.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 ub,fb=g(()=>{"use strict";l();ub={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 gb,hb,zn,yb=g(()=>{"use strict";l();fb();gb=x(require("diff"),1),hb=require("fs"),zn={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:ub,execute:async r=>{let e=r.path,t=r.patch;try{let o=await hb.promises.readFile(e,"utf8"),n=gb.applyPatch(o,t);return n===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
189
299
 
190
- ${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var $y={};te($y,{diffApplyTool:()=>or,diffCreateTool:()=>tr,diffPreviewTool:()=>rr,diffToolsProject:()=>ia});var ia,aa=g(()=>{"use strict";c();by();vy();Ry();ia={manifest:{key:"diff",name:"diff-tools",displayName:"Diff and Patch",version:"1.0.0",description:"Tools to create and apply unified diff changes to files safely.",author:"Sajeer",tools:["diff.create","diff.apply","diff.preview"],category:"diff"},tools:[tr,or,rr],dependencies:{diff:"^7.0.0"}}});var _y,Ey=g(()=>{"use strict";c();_y={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 je,kn=g(()=>{"use strict";c();je=class{connectionString;constructor(e){this.connectionString=e}}});var la,ca,nr,Dy=g(()=>{"use strict";c();la=x(require("better-sqlite3"),1),ca=x(require("fs"),1);kn();nr=class extends je{getDb(){if(!ca.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new la.default(this.connectionString,{readonly:!1})}async query(e,t=[]){let o=this.getDb();try{let r=o.prepare(e);return r.reader?r.all(t):(r.run(t),[])}finally{o.close()}}async execute(e,t=[]){let o=this.getDb();try{let s=o.prepare(e).run(t);return{changes:s.changes,lastInsertRowid:s.lastInsertRowid,raw:s}}finally{o.close()}}async getTables(){return(await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`PRAGMA table_info("${e}")`):await this.query("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")}static executeSession(e,t,o=[]){if(!ca.existsSync(e))throw new Error(`Database file not found: ${e}`);let r=new la.default(e,{readonly:!1});try{let s=r.prepare(t);return s.reader?s.all(o):s.run(o)}finally{r.close()}}}});var My,Rn,Ny=g(()=>{"use strict";c();My=x(require("pg"),1);kn();Rn=class extends je{async getClient(){let e=new My.default.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let o=await this.getClient();try{let r=this.convertSql(e);return(await o.query(r,t)).rows}finally{await o.end()}}async execute(e,t=[]){let o=await this.getClient();try{let r=this.convertSql(e),s=await o.query(r,t);return{changes:s.rowCount??0,raw:s}}finally{await o.end()}}async getTables(){return(await this.query("SELECT tablename as name FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`
300
+ ${n}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var bb={};se(bb,{diffApplyTool:()=>Bn,diffCreateTool:()=>Gn,diffPreviewTool:()=>zn,diffToolsProject:()=>Da});var Da,Ma=g(()=>{"use strict";l();lb();db();yb();Da={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:[Gn,Bn,zn],dependencies:{diff:"^7.0.0"}}});var wb,Tb=g(()=>{"use strict";l();wb={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,Qr=g(()=>{"use strict";l();Ke=class{connectionString;constructor(e){this.connectionString=e}}});var Oa,Na,Hn,xb=g(()=>{"use strict";l();Oa=x(require("better-sqlite3"),1),Na=x(require("fs"),1);Qr();Hn=class extends Ke{getDb(){if(!Na.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Oa.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(!Na.existsSync(e))throw new Error(`Database file not found: ${e}`);let n=new Oa.default(e,{readonly:!1});try{let s=n.prepare(t);return s.reader?s.all(o):s.run(o)}finally{n.close()}}}});var vb,Xr,Cb=g(()=>{"use strict";l();vb=x(require("pg"),1);Qr();Xr=class extends Ke{async getClient(){let e=new vb.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(`
191
301
  SELECT column_name, data_type, is_nullable, column_default
192
302
  FROM information_schema.columns
193
303
  WHERE table_name = $1
@@ -195,7 +305,9 @@ ${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:Str
195
305
  SELECT table_name as name, table_type
196
306
  FROM information_schema.tables
197
307
  WHERE table_schema = 'public'
198
- `)}}});var Ay,$n,Oy=g(()=>{"use strict";c();Ay=x(require("mysql2/promise"),1);kn();$n=class extends je{async getConnection(){return await Ay.default.createConnection(this.connectionString)}async query(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return r}finally{await o.end()}}async execute(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return{changes:r.affectedRows,lastInsertRowid:r.insertId,raw:r}}finally{await o.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let o=Object.keys(t[0]);return t.map(r=>r[o[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[o]=await t.query("DESCRIBE ??",[e]);return o}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var J,Fe=g(()=>{"use strict";c();Dy();Ny();Oy();J=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new Rn(e):e.startsWith("mysql://")?new $n(e):e.startsWith("sqlite://")?new nr(e.replace("sqlite://","")):new nr(e)}}});var sr,Iy=g(()=>{"use strict";c();Ey();Fe();P();sr={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:_y,execute:async n=>{let e=n.db,t=n.sql,o=n.params||[];h(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let s=await J.getAdapter(e).query(t,o);return JSON.stringify(s,null,2)}catch(r){return`Database query error: ${r instanceof Error?r.message:String(r)}`}}}});var Ly,jy=g(()=>{"use strict";c();Ly={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var ir,Fy=g(()=>{"use strict";c();jy();Fe();ir={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Ly,execute:async n=>{let e=n.db,t=n.table;try{let r=await J.getAdapter(e).getSchema(t);return JSON.stringify(r,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var qy,Wy=g(()=>{"use strict";c();qy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var ar,Uy=g(()=>{"use strict";c();Wy();Fe();ar={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:qy,execute:async n=>{let e=n.db;try{let o=await J.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var Gy,By=g(()=>{"use strict";c();Gy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to insert into"},data:{type:"object",description:"Key-value pairs of column names and values to insert"}},required:["db","table","data"]}});var lr,zy=g(()=>{"use strict";c();By();Fe();lr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:Gy,execute:async n=>{let e=n.db,t=n.table,o=n.data;if(Object.keys(o).length===0)return"Error: No data provided to insert.";try{let r=Object.keys(o).join(", "),s=Object.keys(o).map(()=>"?").join(", "),i=Object.values(o),a=`INSERT INTO ${t} (${r}) VALUES (${s})`,p=await J.getAdapter(e).execute(a,i);return JSON.stringify(p,null,2)}catch(r){return`Database insert error: ${r instanceof Error?r.message:String(r)}`}},confirmation:{level:"medium",reason:"This will insert rows into the database, creating permanent records.",showArgs:["table","data"]}}});var Hy,Ky=g(()=>{"use strict";c();Hy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to update"},data:{type:"object",description:"Key-value pairs of column names and new values"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","data","where"]}});var cr,Jy=g(()=>{"use strict";c();Ky();Fe();cr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:Hy,execute:async n=>{let e=n.db,t=n.table,o=n.data,r=n.where;if(Object.keys(o).length===0)return"Error: No data provided to update.";try{let s=Object.keys(o).map(m=>`${m} = ?`).join(", "),i=Object.values(o),a=`UPDATE ${t} SET ${s} WHERE ${r}`,p=await J.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 Qy,Vy=g(()=>{"use strict";c();Qy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var pr,Xy=g(()=>{"use strict";c();Vy();Fe();pr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:Qy,execute:async n=>{let e=n.db,t=n.table,o=n.where;try{let r=`DELETE FROM ${t} WHERE ${o}`,i=await J.getAdapter(e).execute(r);return JSON.stringify(i,null,2)}catch(r){return`Database delete error: ${r instanceof Error?r.message:String(r)}`}},confirmation:{level:"high",reason:"This will permanently delete rows from the database.",showArgs:["table","where"]}}});var Yy,Zy=g(()=>{"use strict";c();Yy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to count rows from"},where:{type:"string",description:"Optional WHERE clause condition"}},required:["db","table"]}});var mr,eb=g(()=>{"use strict";c();Zy();Fe();mr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:Yy,execute:async n=>{let e=n.db,t=n.table,o=n.where;try{let r=o?`WHERE ${o}`:"",s=`SELECT COUNT(*) as count FROM ${t} ${r}`,a=await J.getAdapter(e).query(s);return Array.isArray(a)&&a.length>0?`Rows: ${a[0].count}`:"Count: 0"}catch(r){return`Database count error: ${r instanceof Error?r.message:String(r)}`}}}});var tb={};te(tb,{dbCountTool:()=>mr,dbDeleteTool:()=>pr,dbInsertTool:()=>lr,dbQueryTool:()=>sr,dbSchemaTool:()=>ir,dbTablesTool:()=>ar,dbToolsProject:()=>pa,dbUpdateTool:()=>cr});var pa,ma=g(()=>{"use strict";c();Iy();Fy();Uy();zy();Jy();Xy();eb();pa={manifest:{key:"db",name:"db-tools",displayName:"Database Tools",version:"1.0.0",description:"Stateless database operations enabling the AI to interact with local databases.",author:"Sajeer",tools:["db.query","db.schema","db.tables","db.insert","db.update","db.delete","db.count"],category:"database"},tools:[sr,ir,ar,lr,cr,pr,mr],dependencies:{"better-sqlite3":"^11.3.0"}}});var ob,rb=g(()=>{"use strict";c();ob={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 nb,qe,_n=g(()=>{"use strict";c();nb=require("netlify"),qe=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 nb.NetlifyAPI(e)}}});var dr,sb=g(()=>{"use strict";c();rb();_n();P();dr={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:ob,execute:async n=>{let e=n.siteId,t=n.dir,o=n.message;h(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let s=await qe.getClient().deploy(e,t,{message:o||"Deployed via Toolpack SDK",draft:!1});return JSON.stringify({id:s.deployId,url:s.deploy.url,admin_url:s.deploy.admin_url,state:s.deploy.state},null,2)}catch(r){return`Cloud deployment error: ${r instanceof Error?r.message:String(r)}`}},confirmation:{level:"high",reason:"This will deploy to production (live site).",showArgs:["siteId","dir"]}}});var ib,ab=g(()=>{"use strict";c();ib={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 ur,lb=g(()=>{"use strict";c();ab();_n();ur={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:ib,execute:async n=>{let e=n.siteId,t=n.deployId;try{let r=await qe.getClient().getSiteDeploy({site_id:e,deploy_id:t});return JSON.stringify({id:r.id,state:r.state,error_message:r.error_message,created_at:r.created_at,updated_at:r.updated_at,url:r.url},null,2)}catch(o){return`Cloud status error: ${o instanceof Error?o.message:String(o)}`}}}});var cb,pb=g(()=>{"use strict";c();cb={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 fr,mb=g(()=>{"use strict";c();pb();_n();P();fr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:cb,execute:async n=>{let e=n.siteId,t=n.limit||5;h(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let r=await qe.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(r))return"Unexpected response format from Netlify API";let s=r.map(i=>({id:i.id,state:i.state,created_at:i.created_at,url:i.url,branch:i.branch,title:i.title}));return JSON.stringify(s,null,2)}catch(o){return`Cloud list error: ${o instanceof Error?o.message:String(o)}`}}}});var db={};te(db,{cloudDeployTool:()=>dr,cloudListTool:()=>fr,cloudStatusTool:()=>ur,cloudToolsProject:()=>da});var da,ua=g(()=>{"use strict";c();sb();lb();mb();da={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:[dr,ur,fr],dependencies:{netlify:"^13.1.20"}}});var tx={};te(tx,{AGENT_MODE:()=>ya,AGENT_PLANNING_PROMPT:()=>Gn,AGENT_STEP_PROMPT:()=>Bn,AGENT_WORKFLOW:()=>fa,AIClient:()=>Mo,AnthropicAdapter:()=>Ao,AuthenticationError:()=>ve,BM25SearchEngine:()=>nt,BUILT_IN_MODES:()=>yr,CHAT_MODE:()=>ba,CHAT_WORKFLOW:()=>ha,CODING_MODE:()=>wa,CODING_PLANNING_PROMPT:()=>wb,CODING_STEP_PROMPT:()=>Tb,CODING_WORKFLOW:()=>ga,CONFIG_DIR_NAME:()=>Ca,CONFIG_FILE_NAME:()=>Pa,ConnectionError:()=>_e,ContextWindowConfigError:()=>Yn,ContextWindowExceededError:()=>Cr,ContextWindowStateManager:()=>Rr,ConversationNotFoundError:()=>Zn,DEFAULT_MODE_NAME:()=>et,DEFAULT_TOOLS_CONFIG:()=>V,DEFAULT_TOOL_SEARCH_CONFIG:()=>Aa,DEFAULT_WORKFLOW:()=>HT,DEFAULT_WORKFLOW_CONFIG:()=>zn,GeminiAdapter:()=>Oo,InMemoryConversationStore:()=>Kn,InsufficientContextError:()=>Pr,InvalidRequestError:()=>I,McpClient:()=>bo,McpConnectionError:()=>Te,McpTimeoutError:()=>gr,McpToolManager:()=>hr,ModeRegistry:()=>wo,OllamaAdapter:()=>Ne,OllamaProvider:()=>mt,OpenAIAdapter:()=>Qe,OpenRouterAdapter:()=>Fo,PageError:()=>Vn,Planner:()=>To,ProviderAdapter:()=>Z,ProviderError:()=>W,RateLimitError:()=>Ce,SDKError:()=>N,SQLiteConversationStore:()=>Jn,StepExecutor:()=>vo,SummarizationError:()=>Sr,TOOLPACK_DIR_NAME:()=>va,TOOL_SEARCH_NAME:()=>st,TimeoutError:()=>Xn,ToolDiscoveryCache:()=>Be,ToolRegistry:()=>yo,ToolRouter:()=>at,Toolpack:()=>xa,WorkflowExecutor:()=>br,addBypassRule:()=>el,buildSummarizedHistory:()=>Yb,cloudDeployTool:()=>dr,cloudListTool:()=>fr,cloudStatusTool:()=>ur,cloudToolsProject:()=>da,codingFindSymbolTool:()=>uo,codingGetImportsTool:()=>go,codingGetSymbolsTool:()=>fo,codingToolsProject:()=>ta,countTokens:()=>ts,createContextWindowStateManager:()=>cs,createMcpToolProject:()=>Wn,createMode:()=>xb,createSummarizationReport:()=>Zb,createSummarySystemMessage:()=>kr,createToolProject:()=>ub,dbCountTool:()=>mr,dbDeleteTool:()=>pr,dbInsertTool:()=>lr,dbQueryTool:()=>sr,dbSchemaTool:()=>ir,dbTablesTool:()=>ar,dbToolsProject:()=>pa,dbUpdateTool:()=>cr,diffApplyTool:()=>or,diffCreateTool:()=>tr,diffPreviewTool:()=>rr,diffToolsProject:()=>ia,disconnectMcpToolProject:()=>Un,ensureGlobalConfigDir:()=>Ra,ensureLocalConfigDir:()=>XT,estimateSummaryTokens:()=>Na,estimateTokenCount:()=>Pe,execKillTool:()=>Lt,execListProcessesTool:()=>jt,execReadOutputTool:()=>It,execRunBackgroundTool:()=>Ot,execRunShellTool:()=>At,execRunTool:()=>Nt,execToolsProject:()=>Vs,extractConversationKeypoints:()=>Xb,fetchUrlAsBase64:()=>ys,fsAppendFileTool:()=>yt,fsCopyTool:()=>kt,fsCreateDirTool:()=>Pt,fsDeleteFileTool:()=>wt,fsExistsTool:()=>Tt,fsListDirTool:()=>vt,fsMoveTool:()=>St,fsReadFileRangeTool:()=>$t,fsReadFileTool:()=>ut,fsReplaceInFileTool:()=>Et,fsSearchTool:()=>_t,fsStatTool:()=>xt,fsToolsProject:()=>Us,fsTreeTool:()=>Mt,fsWriteFileTool:()=>gt,generateSummarizationPrompt:()=>Ma,generateToolCategoriesPrompt:()=>$r,getContextWindowPercentage:()=>Kb,getDefaultSlmModel:()=>ol,getGlobalConfigDir:()=>Sa,getGlobalConfigPath:()=>Tr,getGlobalToolpackDir:()=>kb,getLocalConfigDir:()=>ka,getLocalConfigPath:()=>xr,getLocalToolpackDir:()=>Rb,getMessageStats:()=>Vb,getMimeType:()=>us,getOllamaBaseUrl:()=>jo,getOllamaProviderEntries:()=>Za,getRegisteredSlmModels:()=>nl,getRuntimeConfigStatus:()=>ZT,getSafeOutputReserve:()=>os,getToolSearchSchema:()=>it,getToolpackConfig:()=>Mr,getUserHomeDir:()=>Sb,gitAddTool:()=>Qo,gitBlameTool:()=>Xo,gitBranchCreateTool:()=>Zo,gitBranchListTool:()=>Yo,gitCheckoutTool:()=>er,gitCommitTool:()=>Vo,gitDiffTool:()=>Ko,gitLogTool:()=>Jo,gitStatusTool:()=>Ho,gitToolsProject:()=>ra,githubContentsGetTextTool:()=>Xt,githubGraphqlExecuteTool:()=>Vt,githubPrDiffGetTool:()=>to,githubPrFilesListTool:()=>oo,githubPrReviewCommentsReplyTool:()=>eo,githubPrReviewThreadsListTool:()=>Yt,githubPrReviewThreadsResolveTool:()=>Zt,githubPrReviewsSubmitTool:()=>ro,githubToolsProject:()=>Ci,groupMessagesByRole:()=>Qb,handleContextWindowError:()=>Fb,httpDeleteTool:()=>Kt,httpDownloadTool:()=>Qt,httpGetTool:()=>Bt,httpPostTool:()=>zt,httpPutTool:()=>Ht,httpToolsProject:()=>di,initializeGlobalConfigIfFirstRun:()=>ex,isContextWindowError:()=>jb,isDataUri:()=>fs,isRegisteredSlm:()=>rl,isToolSearchTool:()=>Ro,k8sApplyManifestTool:()=>Nn,k8sDeleteResourceTool:()=>An,k8sDescribeTool:()=>Dn,k8sGetConfigMapTool:()=>Ln,k8sGetLogsTool:()=>Mn,k8sGetNamespacesTool:()=>Fn,k8sListDeploymentsTool:()=>In,k8sListPodsTool:()=>En,k8sListServicesTool:()=>On,k8sSwitchContextTool:()=>jn,k8sToolsProject:()=>hb,k8sWaitForDeploymentTool:()=>qn,loadFullConfig:()=>Go,loadRuntimeConfig:()=>YT,loadToolsConfig:()=>so,mergeSummarizationResults:()=>ew,normalizeImagePart:()=>Qa,ollamaRequest:()=>ue,ollamaStream:()=>Ar,parseDataUri:()=>gs,parseSummarizationResponse:()=>ls,prepareSummarizationRequest:()=>as,pruneMessages:()=>ns,readFileAsBase64:()=>hs,reloadToolpackConfig:()=>Nr,removeBypassRule:()=>tl,saveToolsConfig:()=>Ku,systemCwdTool:()=>Ut,systemDiskUsageTool:()=>Gt,systemEnvTool:()=>qt,systemInfoTool:()=>Ft,systemSetEnvTool:()=>Wt,systemToolsProject:()=>si,toDataUri:()=>Ja,toolSearchDefinition:()=>ze,truncateMessage:()=>Jb,validateSummarizationResult:()=>is,webExtractLinksTool:()=>lo,webFetchTool:()=>no,webScrapeTool:()=>ao,webSearchTool:()=>io,webToolsProject:()=>Li,wouldExceedContextWindow:()=>Hb});module.exports=Lb(tx);c();ne();c();var za=require("events");ne();c();ne();var So=class extends N{constructor(t,o,r,s,i,a){super(t,"CONTEXT_WINDOW_EXCEEDED",400,a);this.conversationId=o;this.currentTokens=r;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`
308
+ `)}}});var kb,Yr,Pb=g(()=>{"use strict";l();kb=x(require("mysql2/promise"),1);Qr();Yr=class extends Ke{async getConnection(){return await kb.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 X,Je=g(()=>{"use strict";l();xb();Cb();Pb();X=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new Xr(e):e.startsWith("mysql://")?new Yr(e):e.startsWith("sqlite://")?new Hn(e.replace("sqlite://","")):new Hn(e)}}});var Kn,Sb=g(()=>{"use strict";l();Tb();Je();k();Kn={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:wb,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 X.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 Rb,_b=g(()=>{"use strict";l();Rb={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 Jn,$b=g(()=>{"use strict";l();_b();Je();Jn={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Rb,execute:async r=>{let e=r.db,t=r.table;try{let n=await X.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var Eb,Db=g(()=>{"use strict";l();Eb={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var Vn,Mb=g(()=>{"use strict";l();Db();Je();Vn={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:Eb,execute:async r=>{let e=r.db;try{let o=await X.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var Ob,Nb=g(()=>{"use strict";l();Ob={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 Qn,Ab=g(()=>{"use strict";l();Nb();Je();Qn={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:Ob,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 X.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 Ib,Lb=g(()=>{"use strict";l();Ib={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 Xn,jb=g(()=>{"use strict";l();Lb();Je();Xn={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:Ib,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 X.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 Fb,qb=g(()=>{"use strict";l();Fb={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 Yn,Wb=g(()=>{"use strict";l();qb();Je();Yn={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:Fb,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await X.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 Ub,Gb=g(()=>{"use strict";l();Ub={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 Zn,Bb=g(()=>{"use strict";l();Gb();Je();Zn={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:Ub,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 X.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 zb={};se(zb,{dbCountTool:()=>Zn,dbDeleteTool:()=>Yn,dbInsertTool:()=>Qn,dbQueryTool:()=>Kn,dbSchemaTool:()=>Jn,dbTablesTool:()=>Vn,dbToolsProject:()=>Aa,dbUpdateTool:()=>Xn});var Aa,Ia=g(()=>{"use strict";l();Sb();$b();Mb();Ab();jb();Wb();Bb();Aa={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:[Kn,Jn,Vn,Qn,Xn,Yn,Zn],dependencies:{"better-sqlite3":"^11.3.0"}}});var Hb,Kb=g(()=>{"use strict";l();Hb={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 Jb,Ve,Zr=g(()=>{"use strict";l();Jb=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 Jb.NetlifyAPI(e)}}});var er,Vb=g(()=>{"use strict";l();Kb();Zr();k();er={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:Hb,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 Qb,Xb=g(()=>{"use strict";l();Qb={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 tr,Yb=g(()=>{"use strict";l();Xb();Zr();tr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:Qb,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 Zb,ew=g(()=>{"use strict";l();Zb={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 or,tw=g(()=>{"use strict";l();ew();Zr();k();or={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Zb,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 ow={};se(ow,{cloudDeployTool:()=>er,cloudListTool:()=>or,cloudStatusTool:()=>tr,cloudToolsProject:()=>La});var La,ja=g(()=>{"use strict";l();Vb();Yb();tw();La={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:[er,tr,or],dependencies:{netlify:"^13.1.20"}}});var nw,rw,sw,iw,aw,lw=g(()=>{"use strict";l();nw="slack.chat.postMessage",rw="Post Slack Message",sw="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.",iw="slack",aw={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 fe(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 mt=g(()=>{"use strict";l()});function Rv(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}}async function ge(r,e,t){let o=await fetch(`https://slack.com/api/${r}`,{method:"POST",headers:Rv(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 dt=g(()=>{"use strict";l()});async function _v(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=fe(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 ge("chat.postMessage",s,i),c=a.ts??"";return`Message posted. channel=${a.channel??e} ts=${c}`}var Qo,Fa=g(()=>{"use strict";l();lw();mt();dt();Qo={name:nw,displayName:rw,description:sw,parameters:aw,category:iw,execute:_v}});var cw,pw,mw,dw,uw,fw=g(()=>{"use strict";l();cw="slack.chat.postEphemeral",pw="Post Ephemeral Slack Message",mw="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.",dw="slack",uw={type:"object",properties:{channel:{type:"string",description:"Channel ID where the ephemeral message will appear."},user:{type:"string",description:"Slack user ID of the person who will see the message."},text:{type:"string",description:"Message text in Slack mrkdwn format."},thread_ts:{type:"string",description:"Timestamp of the parent message to show the ephemeral reply inside a thread."},token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:["channel","user","text"]}});async function $v(r){let e=String(r.channel),t=String(r.user),o=String(r.text),n=r.thread_ts?String(r.thread_ts):void 0,s=fe(r.token),i={channel:e,user:t,text:o};return n&&(i.thread_ts=n),await ge("chat.postEphemeral",s,i),`Ephemeral message sent to user=${t} in channel=${e}.`}var Xo,qa=g(()=>{"use strict";l();fw();mt();dt();Xo={name:cw,displayName:pw,description:mw,parameters:uw,category:dw,execute:$v}});var gw,hw,yw,bw,ww,Tw=g(()=>{"use strict";l();gw="slack.reactions.add",hw="Add Slack Reaction",yw="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.",bw="slack",ww={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 Ev(r){let e=String(r.channel),t=String(r.timestamp),o=String(r.name),n=fe(r.token);try{await ge("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 Yo,Wa=g(()=>{"use strict";l();Tw();mt();dt();Yo={name:gw,displayName:hw,description:yw,parameters:ww,category:bw,execute:Ev}});var xw,vw,Cw,kw,Pw,Sw=g(()=>{"use strict";l();xw="slack.conversations.history",vw="Get Slack Channel History",Cw="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.",kw="slack",Pw={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 Dv(r){let e=String(r.channel),t=typeof r.limit=="number"?Math.min(r.limit,100):10,o=fe(r.token),n={channel:e,limit:t};r.oldest&&(n.oldest=String(r.oldest)),r.latest&&(n.latest=String(r.latest));let i=(await ge("conversations.history",o,n)).messages??[];return i.length===0?"No messages found.":[...i].reverse().map(c=>{let p=c.user?`user:${c.user}`:c.bot_id?`bot:${c.bot_id}`:"unknown",m=c.reply_count?` [thread: ${c.reply_count} replies]`:"",u=(c.text??"").replace(/\n/g," ").slice(0,200);return`[${c.ts}] ${p}${m}: ${u}`}).join(`
309
+ `)}var Zo,Ua=g(()=>{"use strict";l();Sw();mt();dt();Zo={name:xw,displayName:vw,description:Cw,parameters:Pw,category:kw,execute:Dv}});var Rw,_w,$w,Ew,Dw,Mw=g(()=>{"use strict";l();Rw="slack.conversations.replies",_w="Get Slack Thread Replies",$w="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.",Ew="slack",Dw={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 Mv(r){let e=String(r.channel),t=String(r.ts),o=typeof r.limit=="number"?Math.min(r.limit,100):20,n=fe(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 ge("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 en,Ga=g(()=>{"use strict";l();Mw();mt();dt();en={name:Rw,displayName:_w,description:$w,parameters:Dw,category:Ew,execute:Mv}});var Ow,Nw,Aw,Iw,Lw,jw=g(()=>{"use strict";l();Ow="slack.auth.test",Nw="Slack Auth Test",Aw="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.",Iw="slack",Lw={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function Ov(r){let e=fe(r.token),t=await ge("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 tn,Ba=g(()=>{"use strict";l();jw();mt();dt();tn={name:Ow,displayName:Nw,description:Aw,parameters:Lw,category:Iw,execute:Ov}});var Fw={};se(Fw,{slackAuthTestTool:()=>tn,slackChatPostEphemeralTool:()=>Xo,slackChatPostMessageTool:()=>Qo,slackConversationsHistoryTool:()=>Zo,slackConversationsRepliesTool:()=>en,slackReactionsAddTool:()=>Yo,slackToolsProject:()=>za});var za,Ha=g(()=>{"use strict";l();Fa();qa();Wa();Ua();Ga();Ba();Fa();qa();Wa();Ua();Ga();Ba();za={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:[Qo,Xo,Yo,Zo,en,tn]}});var Xv={};se(Xv,{AGENT_MODE:()=>Za,AGENT_PLANNING_PROMPT:()=>us,AGENT_WORKFLOW:()=>Qa,AIClient:()=>bn,AnthropicAdapter:()=>Tn,AuthenticationError:()=>de,BM25SearchEngine:()=>bt,BUILT_IN_MODES:()=>sr,CHAT_MODE:()=>el,CHAT_WORKFLOW:()=>Ya,CODING_MODE:()=>tl,CODING_PLANNING_PROMPT:()=>Jw,CODING_WORKFLOW:()=>Xa,CONFIG_DIR_NAME:()=>sl,CONFIG_FILE_NAME:()=>il,ConnectionError:()=>Ie,ContextWindowConfigError:()=>Cs,ContextWindowExceededError:()=>mr,ContextWindowStateManager:()=>gr,ConversationNotFoundError:()=>ks,DEFAULT_MODE_NAME:()=>ft,DEFAULT_TOOLS_CONFIG:()=>Z,DEFAULT_TOOL_SEARCH_CONFIG:()=>yl,DEFAULT_WORKFLOW:()=>Uv,DEFAULT_WORKFLOW_CONFIG:()=>fs,GeminiAdapter:()=>vn,InMemoryConversationStore:()=>hs,InsufficientContextError:()=>dr,InvalidRequestError:()=>I,McpClient:()=>nn,McpConnectionError:()=>$e,McpTimeoutError:()=>nr,McpToolManager:()=>rr,ModeRegistry:()=>rn,OllamaAdapter:()=>qe,OllamaProvider:()=>Pt,OpenAIAdapter:()=>st,OpenRouterAdapter:()=>Sn,PageError:()=>xs,Planner:()=>sn,ProviderAdapter:()=>Q,ProviderError:()=>F,RateLimitError:()=>Te,SDKError:()=>N,SQLiteConversationStore:()=>ys,SummarizationError:()=>ur,TOOLPACK_DIR_NAME:()=>rl,TOOL_SEARCH_NAME:()=>wt,TimeoutError:()=>vs,ToolDiscoveryCache:()=>et,ToolRegistry:()=>on,ToolRouter:()=>xt,Toolpack:()=>nl,VertexAIAdapter:()=>xn,WorkflowExecutor:()=>ir,addBypassRule:()=>Il,buildSummarizedHistory:()=>ST,cloudDeployTool:()=>er,cloudListTool:()=>or,cloudStatusTool:()=>tr,cloudToolsProject:()=>La,codingExtractFunctionTool:()=>Jo,codingFindReferencesTool:()=>qo,codingFindSymbolTool:()=>Lo,codingGetCallHierarchyTool:()=>Vo,codingGetDiagnosticsTool:()=>Ho,codingGetExportsTool:()=>Ko,codingGetImportsTool:()=>Fo,codingGetOutlineTool:()=>zo,codingGetSymbolsTool:()=>jo,codingGoToDefinitionTool:()=>Wo,codingMultiFileEditTool:()=>Uo,codingRefactorRenameTool:()=>Bo,codingToolsProject:()=>Sa,countTokens:()=>Ss,createContextWindowStateManager:()=>Ns,createMcpToolProject:()=>ms,createMode:()=>Vw,createSkillInterceptor:()=>rT,createSkillTools:()=>Kw,createSummarizationReport:()=>RT,createSummarySystemMessage:()=>fr,createToolProject:()=>qw,dbCountTool:()=>Zn,dbDeleteTool:()=>Yn,dbInsertTool:()=>Qn,dbQueryTool:()=>Kn,dbSchemaTool:()=>Jn,dbTablesTool:()=>Vn,dbToolsProject:()=>Aa,dbUpdateTool:()=>Xn,diffApplyTool:()=>Bn,diffCreateTool:()=>Gn,diffPreviewTool:()=>zn,diffToolsProject:()=>Da,disconnectMcpToolProject:()=>ds,ensureGlobalConfigDir:()=>cl,ensureLocalConfigDir:()=>zv,estimateSummaryTokens:()=>hl,estimateTokenCount:()=>Me,execKillTool:()=>to,execListProcessesTool:()=>oo,execReadOutputTool:()=>eo,execRunBackgroundTool:()=>Zt,execRunShellTool:()=>Yt,execRunTool:()=>Xt,execToolsProject:()=>Ti,extractConversationKeypoints:()=>PT,fetchUrlAsBase64:()=>Ws,fsAppendFileTool:()=>Dt,fsBatchReadTool:()=>Vt,fsBatchWriteTool:()=>Qt,fsCopyTool:()=>qt,fsCreateDirTool:()=>jt,fsDeleteDirTool:()=>Jt,fsDeleteFileTool:()=>Ot,fsExistsTool:()=>Nt,fsGlobTool:()=>Kt,fsListDirTool:()=>It,fsMoveTool:()=>Ft,fsReadFileRangeTool:()=>Ut,fsReadFileTool:()=>Rt,fsReplaceInFileTool:()=>Bt,fsSearchTool:()=>Gt,fsStatTool:()=>At,fsToolsProject:()=>di,fsTreeTool:()=>Ht,fsWriteFileTool:()=>$t,generateSummarizationPrompt:()=>gl,generateToolCategoriesPrompt:()=>hr,getContextWindowPercentage:()=>xT,getDefaultSlmModel:()=>jl,getGlobalConfigDir:()=>al,getGlobalConfigPath:()=>lr,getGlobalToolpackDir:()=>eT,getLocalConfigDir:()=>ll,getLocalConfigPath:()=>cr,getLocalToolpackDir:()=>tT,getMessageStats:()=>kT,getMimeType:()=>Ls,getOllamaBaseUrl:()=>Pn,getOllamaProviderEntries:()=>Al,getRegisteredSlmModels:()=>ql,getRuntimeConfigStatus:()=>Kv,getSafeOutputReserve:()=>Rs,getToolSearchSchema:()=>Tt,getToolpackConfig:()=>Tr,getUserHomeDir:()=>Zw,gitAddTool:()=>In,gitBlameTool:()=>jn,gitBranchCreateTool:()=>qn,gitBranchListTool:()=>Fn,gitCheckoutTool:()=>Wn,gitCloneTool:()=>Un,gitCommitTool:()=>Ln,gitDiffTool:()=>Nn,gitLogTool:()=>An,gitStatusTool:()=>On,gitToolsProject:()=>_a,githubContentsGetTextTool:()=>ho,githubGraphqlExecuteTool:()=>go,githubIssuesCommentsCreateTool:()=>Co,githubPrDiffGetTool:()=>To,githubPrFilesListTool:()=>xo,githubPrReviewCommentsReplyTool:()=>wo,githubPrReviewThreadsListTool:()=>yo,githubPrReviewThreadsResolveTool:()=>bo,githubPrReviewsSubmitTool:()=>vo,githubToolsProject:()=>Ki,groupMessagesByRole:()=>CT,handleContextWindowError:()=>uT,httpDeleteTool:()=>mo,httpDownloadTool:()=>fo,httpGetTool:()=>lo,httpPostTool:()=>co,httpPutTool:()=>po,httpToolsProject:()=>Ii,initializeGlobalConfigIfFirstRun:()=>Jv,isContextWindowError:()=>dT,isDataUri:()=>js,isRegisteredSlm:()=>Fl,isToolSearchTool:()=>un,k8sApplyManifestTool:()=>ns,k8sDeleteResourceTool:()=>rs,k8sDescribeTool:()=>ts,k8sGetConfigMapTool:()=>as,k8sGetLogsTool:()=>os,k8sGetNamespacesTool:()=>cs,k8sListDeploymentsTool:()=>is,k8sListPodsTool:()=>es,k8sListServicesTool:()=>ss,k8sSwitchContextTool:()=>ls,k8sToolsProject:()=>Gw,k8sWaitForDeploymentTool:()=>ps,loadFullConfig:()=>En,loadRuntimeConfig:()=>Hv,loadToolsConfig:()=>Po,mergeSummarizationResults:()=>_T,normalizeImagePart:()=>El,ollamaRequest:()=>ve,ollamaStream:()=>vr,parseDataUri:()=>Fs,parseSummarizationResponse:()=>Os,prepareSummarizationRequest:()=>Ms,pruneMessages:()=>$s,readFileAsBase64:()=>qs,reloadToolpackConfig:()=>xr,removeBypassRule:()=>Ll,saveToolsConfig:()=>Ef,slackAuthTestTool:()=>tn,slackChatPostEphemeralTool:()=>Xo,slackChatPostMessageTool:()=>Qo,slackConversationsHistoryTool:()=>Zo,slackConversationsRepliesTool:()=>en,slackReactionsAddTool:()=>Yo,slackToolsProject:()=>za,systemCwdTool:()=>io,systemDiskUsageTool:()=>ao,systemEnvTool:()=>ro,systemInfoTool:()=>no,systemSetEnvTool:()=>so,systemToolsProject:()=>$i,toDataUri:()=>$l,toolSearchDefinition:()=>tt,truncateMessage:()=>vT,validateSummarizationResult:()=>Ds,webExtractLinksTool:()=>_o,webFeedTool:()=>Mo,webFetchTool:()=>ko,webMapTool:()=>$o,webMetadataTool:()=>Eo,webScrapeTool:()=>Ro,webScreenshotTool:()=>Oo,webSearchTool:()=>So,webSitemapTool:()=>Do,webToolsProject:()=>aa,wouldExceedContextWindow:()=>TT});module.exports=mT(Xv);l();ce();l();var Sl=require("events");ce();l();ce();var mn=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`
199
311
  Context Window Exceeded
200
312
  =======================
201
313
  Conversation ID: ${this.conversationId}
@@ -206,7 +318,7 @@ Usage: ${this.getUsagePercentage()}%
206
318
  Strategy: ${this.strategy}
207
319
 
208
320
  Message: ${this.message}
209
- `.trim()}};var ko=class extends N{constructor(t,o,r,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=r;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=`
321
+ `.trim()}};var dn=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=`
210
322
  Summarization Error
211
323
  ===================
212
324
  Conversation ID: ${this.conversationId}
@@ -218,11 +330,11 @@ Recovery Action: ${this.getSuggestedRecovery()}
218
330
  Message: ${this.message}`;return this.summaryAttempt?t+`
219
331
 
220
332
  Partial Summary:
221
- ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}};c();var es=null;async function qb(){if(!es)try{es=await import("js-tiktoken")}catch{}return es}var Da={"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},Wb=2;async function Ub(n,e){try{let t=await qb();if(!t)return Pe(n);let o=t.encoding_for_model(e),r=0,s=Da[e]??Da.__default__;for(let i of n){if(r+=s,typeof i.content=="string")r+=o.encode(i.content).length;else if(Array.isArray(i.content))for(let a of i.content)a.type==="text"?r+=o.encode(a.text).length:(a.type==="image_data"||a.type==="image_url"||a.type==="image_file")&&(r+=256);if(i.tool_calls?.length)for(let a of i.tool_calls)r+=o.encode(a.function.name).length,r+=o.encode(a.function.arguments).length;i.name&&(r+=o.encode(i.name).length)}return r+=Wb,r}catch{return Pe(n)}}async function Gb(n,e){try{let t=Pe(n);return Math.ceil(t*1.1)}catch{return Pe(n)}}async function Bb(n,e){try{let t=Pe(n);return Math.ceil(t*1.05)}catch{return Pe(n)}}async function zb(n,e){let t=Pe(n);return Math.ceil(t*1.05)}function Pe(n){let e=0;for(let t of n){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 ts(n,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?Ub(n,e):o==="anthropic"||o==="claude"?Gb(n,e):o==="gemini"||o==="google"?Bb(n,e):o==="ollama"?zb(n,e):Pe(n)}function Hb(n,e,t){let o=e-t;return n>o}function Kb(n,e){return Math.round(n/e*100)}function os(n,e=1.15){return Math.ceil(n*e)}c();function ns(n,e,t=!0){let o=n.length,r=[],s=0,i=[];n.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=rs(p);if(s+=m,r.push(p),p.role==="assistant"&&p.tool_calls?.length){let d=new Set(p.tool_calls.map(f=>f.id));for(let f of n)f.role==="tool"&&f.tool_call_id&&d.has(f.tool_call_id)&&(s+=rs(f),r.push(f))}}let a=new Set(r),l=n.filter(p=>!a.has(p));return{removed:r.length,tokensReclaimed:s,newTotal:l.length,pruneInfo:{beforeCount:o,afterCount:l.length,removedMessages:r}}}function Jb(n,e){if(typeof n.content=="string"){let t=e*4;if(n.content.length<=t)return n;let o=n.content.substring(0,t),r=Math.ceil((n.content.length-t)/4);return{...n,content:`${o}
333
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}};l();var Ps=null;async function fT(){if(!Ps)try{Ps=await import("js-tiktoken")}catch{}return Ps}var fl={"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},gT=2;async function hT(r,e){try{let t=await fT();if(!t)return Me(r);let o=t.encoding_for_model(e),n=0,s=fl[e]??fl.__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+=gT,n}catch{return Me(r)}}async function yT(r,e){try{let t=Me(r);return Math.ceil(t*1.1)}catch{return Me(r)}}async function bT(r,e){try{let t=Me(r);return Math.ceil(t*1.05)}catch{return Me(r)}}async function wT(r,e){let t=Me(r);return Math.ceil(t*1.05)}function Me(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 Ss(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?hT(r,e):o==="anthropic"||o==="claude"?yT(r,e):o==="gemini"||o==="google"?bT(r,e):o==="ollama"?wT(r,e):Me(r)}function TT(r,e,t){let o=e-t;return r>o}function xT(r,e){return Math.round(r/e*100)}function Rs(r,e=1.15){return Math.ceil(r*e)}l();function $s(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),c=r.filter(p=>!a.has(p));return{removed:n.length,tokensReclaimed:s,newTotal:c.length,pruneInfo:{beforeCount:o,afterCount:c.length,removedMessages:n}}}function vT(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}
222
334
 
223
- [...truncated ${r} tokens]`}}else if(Array.isArray(n.content)){let t=n.content.filter(a=>a.type==="text"),o=t.reduce((a,l)=>a+(l.text?.length||0),0),r=e*4;if(o<=r)return n;let s=0,i=[];for(let a of t)if(a.type==="text"){let l=r-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}
335
+ [...truncated ${n} tokens]`}}else if(Array.isArray(r.content)){let t=r.content.filter(a=>a.type==="text"),o=t.reduce((a,c)=>a+(c.text?.length||0),0),n=e*4;if(o<=n)return r;let s=0,i=[];for(let a of t)if(a.type==="text"){let c=n-s;if(c<=0)break;let p=a.text;if(p.length<=c)i.push(a),s+=p.length;else{let m=p.substring(0,c),u=Math.ceil((p.length-c)/4);i.push({type:"text",text:`${m}
224
336
 
225
- [...truncated ${d} tokens]`});break}}return{...n,content:i.length>0?i:n.content}}return n}function rs(n){let e=4;if(typeof n.content=="string")e+=Math.ceil(n.content.length/4);else if(Array.isArray(n.content))for(let t of n.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(n.tool_calls?.length)for(let t of n.tool_calls)e+=Math.ceil(t.function.name.length/4),e+=Math.ceil(t.function.arguments.length/4);return n.name&&(e+=Math.ceil(n.name.length/4)),e}function Qb(n){let e={system:[],user:[],assistant:[],tool:[]};return n.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function Vb(n){let e=0,t={},o=0;for(let r of n){let s=rs(r);e+=s,o=Math.max(o,s),t[r.role]??=0,t[r.role]++}return{totalMessages:n.length,totalTokens:e,byRole:t,largestMessageTokens:o}}c();ne();function ss(n){return n.content==null?"":typeof n.content=="string"?n.content:n.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 Ma(n,e){if(e)return e;let t=n.filter(l=>l.role==="user"),o=n.filter(l=>l.role==="assistant"),r=n.filter(l=>l.role==="tool"),s=n.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${r.length>0?`, and ${r.length} tool responses`:""}).
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 CT(r){let e={system:[],user:[],assistant:[],tool:[]};return r.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function kT(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}}l();ce();function Es(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 gl(r,e){if(e)return e;let t=r.filter(c=>c.role==="user"),o=r.filter(c=>c.role==="assistant"),n=r.filter(c=>c.role==="tool"),s=r.length,i=t.length,a=o.length;return`Please provide a concise summary of the following conversation history. The conversation contains ${s} messages (${i} user messages, ${a} assistant responses${n.length>0?`, and ${n.length} tool responses`:""}).
226
338
 
227
339
  Focus on:
228
340
  1. Key topics discussed
@@ -234,32 +346,32 @@ The summary should be comprehensive yet concise, preserving all critical informa
234
346
 
235
347
  ---
236
348
  CONVERSATION:
237
- ${n.map((l,p)=>{let m=ss(l);return`[Message ${p+1}] ${l.role.toUpperCase()}: ${m.substring(0,200)}${m.length>200?"...":""}`}).join(`
349
+ ${r.map((c,p)=>{let m=Es(c);return`[Message ${p+1}] ${c.role.toUpperCase()}: ${m.substring(0,200)}${m.length>200?"...":""}`}).join(`
238
350
  `)}
239
351
  ---
240
352
 
241
- SUMMARY:`}function kr(n,e){return{role:"system",content:`[Context Summary]
353
+ SUMMARY:`}function fr(r,e){return{role:"system",content:`[Context Summary]
242
354
  This conversation has been summarized to manage context window. The following is a summary of the first ${e} messages:
243
355
 
244
- ${n}
356
+ ${r}
245
357
 
246
358
  [End Summary]
247
359
 
248
- Use this summary to understand the conversation context. When responding, acknowledge that you're aware of the previous conversation and continue naturally.`}}function Xb(n){let e=new Set,t=[],o=[],r="";for(let s of n)if(s.role==="user"){let i=ss(s);r=i,i.includes("?")&&o.push(i.split(`
249
- `)[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=ss(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:r.substring(0,200)}}function Na(n){return Math.ceil(n.length/4)}function is(n){let e=[];return(!n.summary||n.summary.length<10)&&e.push("Summary is too short"),n.summary.length>5e3&&e.push("Summary is excessively long"),n.messageCount<2&&e.push("Must summarize at least 2 messages"),n.summaryTokens>=n.originalTokens*.8&&e.push("Summary is not significantly shorter than original messages"),n.tokensSaved<0&&e.push("Token calculation error: saved tokens is negative"),{valid:e.length===0,issues:e}}function as(n,e){let t=Ma(n,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.
360
+ Use this summary to understand the conversation context. When responding, acknowledge that you're aware of the previous conversation and continue naturally.`}}function PT(r){let e=new Set,t=[],o=[],n="";for(let s of r)if(s.role==="user"){let i=Es(s);n=i,i.includes("?")&&o.push(i.split(`
361
+ `)[0]);let a=i.match(/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b/g);a&&a.forEach(c=>e.add(c))}else if(s.role==="assistant"){let i=Es(s);if(i.includes("decided")||i.includes("concluded")||i.includes("determined")){let a=i.split(/[.!?]+/);for(let c of a)(c.includes("decided")||c.includes("concluded")||c.includes("determined"))&&t.push(c.trim())}}return{topics:Array.from(e).slice(0,10),decisions:t.slice(0,5),userGoals:o.slice(0,5),context:n.substring(0,200)}}function hl(r){return Math.ceil(r.length/4)}function Ds(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 Ms(r,e){let t=gl(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.
250
362
 
251
363
  Maximum summary length: ${e.maxSummaryTokens||500} tokens.
252
- Format: Write only the summary without any additional commentary.`},{role:"user",content:t}]}function ls(n,e,t){let o=Na(n),r=Math.max(0,t-o);return{summary:n.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:r,timestamp:new Date}}function Yb(n,e,t){let o=[...n];return o.push(kr(e.summary,e.messageCount)),o.push(...t),o}function Zb(n,e,t){let o=Math.round(n.tokensSaved/n.originalTokens*100);return`
364
+ Format: Write only the summary without any additional commentary.`},{role:"user",content:t}]}function Os(r,e,t){let o=hl(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function ST(r,e,t){let o=[...r];return o.push(fr(e.summary,e.messageCount)),o.push(...t),o}function RT(r,e,t){let o=Math.round(r.tokensSaved/r.originalTokens*100);return`
253
365
  Summarization Report
254
366
  ====================
255
- Timestamp: ${n.timestamp.toISOString()}
367
+ Timestamp: ${r.timestamp.toISOString()}
256
368
  Status: \u2713 Summarization completed
257
369
 
258
370
  Input Analysis:
259
- - Messages summarized: ${n.messageCount}
260
- - Original token count: ${n.originalTokens}
261
- - Summary token count: ${n.summaryTokens}
262
- - Tokens saved: ${n.tokensSaved} (${o}% reduction)
371
+ - Messages summarized: ${r.messageCount}
372
+ - Original token count: ${r.originalTokens}
373
+ - Summary token count: ${r.summaryTokens}
374
+ - Tokens saved: ${r.tokensSaved} (${o}% reduction)
263
375
 
264
376
  Message Count:
265
377
  - Before: ${e} messages
@@ -267,52 +379,41 @@ Message Count:
267
379
  - Reduction: ${e-t} messages
268
380
 
269
381
  Summary Preview:
270
- ${n.summary.substring(0,300)}${n.summary.length>300?"...":""}
271
- `.trim()}function ew(n){if(n.length===0)throw new N("Cannot merge empty summarization results","CONTEXT_WINDOW_ERROR");return{summary:n.map(t=>`[Round ${n.indexOf(t)+1}] ${t.summary}`).join(`
382
+ ${r.summary.substring(0,300)}${r.summary.length>300?"...":""}
383
+ `.trim()}function _T(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(`
272
384
 
273
- `),messageCount:n.reduce((t,o)=>t+o.messageCount,0),originalTokens:n.reduce((t,o)=>t+o.originalTokens,0),summaryTokens:n.reduce((t,o)=>t+o.summaryTokens,0),tokensSaved:n.reduce((t,o)=>t+o.tokensSaved,0),timestamp:new Date}}c();var Rr=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,r=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:r}}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(r=>r.estimatedTokens>o&&r.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}`,""],r=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(r/e.length);o.push("Summary:"),o.push(`- Total tokens across all conversations: ${r}`),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(`
274
- `)}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[r,s]of this.states.entries())s.lastUpdated<t&&o.push(r);return o.forEach(r=>this.states.delete(r)),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 cs(n){return new Rr(n)}c();c();c();var rt={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},nt=class{documents=[];avgDocLength=0;idf=new Map;totalDocs=0;docFrequencies=new Map;k1=1.2;b=.75;index(e){this.documents=[],this.docFrequencies.clear(),this.idf.clear();for(let t of e){let o=this.createDocument(t);this.documents.push(o);let r=new Set(o.tokens);for(let s of r)this.docFrequencies.set(s,(this.docFrequencies.get(s)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let o=t?.limit??5,r=t?.category,s=t?.minScore??0,i=this.tokenize(e.toLowerCase());if(i.length===0)return[];let a=[];for(let l of this.documents){if(r&&l.tool.category!==r)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<rt.name;i++)t.push(e.name);for(let i=0;i<rt.displayName;i++)t.push(e.displayName);for(let i=0;i<rt.description;i++)t.push(e.description);for(let i=0;i<rt.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<rt.parameterNames;l++)t.push(i);if(a.description)for(let l=0;l<rt.parameterDescriptions;l++)t.push(a.description)}let o=t.join(" ").toLowerCase(),r=this.tokenize(o),s=this.computeTermFrequencies(r);return{toolName:e.name,tool:e,text:o,tokens:r,length:r.length,termFrequencies:s}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!tw.has(t))}computeTermFrequencies(e){let t=new Map;for(let o of e)t.set(o,(t.get(o)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let o=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,o)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,o)=>t+o.length,0)/this.documents.length}computeBM25Score(e,t){let o=0;for(let r of e){let s=t.termFrequencies.get(r)||0;if(s===0)continue;let i=this.idf.get(r)||0,a=t.length,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}}},tw=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 Be=class n{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let o of t)this.discoveredTools.add(o);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new n;for(let o of e)if(o.role==="tool"){let r=o;if(typeof r.content=="string")try{let s=JSON.parse(r.content);if(s.query&&s.tools&&Array.isArray(s.tools)){let i=s.tools.map(a=>typeof a=="string"?a:a.name).filter(Boolean);i.length>0&&t.recordDiscovery(s.query,i)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}};c();var st="tool.search",ze={name:st,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
385
+ `),messageCount:r.reduce((t,o)=>t+o.messageCount,0),originalTokens:r.reduce((t,o)=>t+o.originalTokens,0),summaryTokens:r.reduce((t,o)=>t+o.summaryTokens,0),tokensSaved:r.reduce((t,o)=>t+o.tokensSaved,0),timestamp:new Date}}l();var gr=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 c=this.getAtRiskConversations();c.length>0&&(o.push(`At-Risk Conversations (80%+ threshold): ${c.length}`),c.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 Ns(r){return new gr(r)}l();l();l();var yt={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},bt=class{documents=[];avgDocLength=0;idf=new Map;totalDocs=0;docFrequencies=new Map;k1=1.2;b=.75;index(e){this.documents=[],this.docFrequencies.clear(),this.idf.clear();for(let t of e){let o=this.createDocument(t);this.documents.push(o);let n=new Set(o.tokens);for(let s of n)this.docFrequencies.set(s,(this.docFrequencies.get(s)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let o=t?.limit??5,n=t?.category,s=t?.minScore??0,i=this.tokenize(e.toLowerCase());if(i.length===0)return[];let a=[];for(let c of this.documents){if(n&&c.tool.category!==n)continue;let p=this.computeBM25Score(i,c);p>s&&a.push({toolName:c.toolName,score:p,tool:c.tool})}return a.sort((c,p)=>p.score-c.score).slice(0,o).map(({toolName:c,score:p,tool:m})=>({toolName:c,score:p,tool:this.toSchema(m)}))}getIndexedCount(){return this.documents.length}isIndexed(e){return this.documents.some(t=>t.toolName===e)}createDocument(e){let t=[];for(let i=0;i<yt.name;i++)t.push(e.name);for(let i=0;i<yt.displayName;i++)t.push(e.displayName);for(let i=0;i<yt.description;i++)t.push(e.description);for(let i=0;i<yt.category;i++)t.push(e.category);if(e.parameters?.properties)for(let[i,a]of Object.entries(e.parameters.properties)){for(let c=0;c<yt.parameterNames;c++)t.push(i);if(a.description)for(let c=0;c<yt.parameterDescriptions;c++)t.push(a.description)}let o=t.join(" ").toLowerCase(),n=this.tokenize(o),s=this.computeTermFrequencies(n);return{toolName:e.name,tool:e,text:o,tokens:n,length:n.length,termFrequencies:s}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!$T.has(t))}computeTermFrequencies(e){let t=new Map;for(let o of e)t.set(o,(t.get(o)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let o=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,o)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,o)=>t+o.length,0)/this.documents.length}computeBM25Score(e,t){let o=0;for(let n of e){let s=t.termFrequencies.get(n)||0;if(s===0)continue;let i=this.idf.get(n)||0,a=t.length,c=s*(this.k1+1),p=s+this.k1*(1-this.b+this.b*(a/this.avgDocLength));o+=i*(c/p)}return o}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},$T=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there"]);l();var et=class r{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let o of t)this.discoveredTools.add(o);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new r;for(let o of e)if(o.role==="tool"){let n=o;if(typeof n.content=="string")try{let s=JSON.parse(n.content);if(s.query&&s.tools&&Array.isArray(s.tools)){let i=s.tools.map(a=>typeof a=="string"?a:a.name).filter(Boolean);i.length>0&&t.recordDiscovery(s.query,i)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}};l();var wt="tool.search",tt={name:wt,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
275
387
  Use this to discover tools before using them.
276
388
  Examples: "file operations", "web scraping", "run command", "http request"
277
389
 
278
390
  Returns a list of matching tools with their names, descriptions, and parameters.
279
- 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 it(){return{name:ze.name,displayName:ze.displayName,description:ze.description,parameters:ze.parameters,category:ze.category}}function Ro(n){return n===st}c();var ow={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 $r(n){let e=n.getCategories();if(e.length===0)return"No tools are currently available.";let t=["You have access to tools in the following categories:",""];for(let o of e){let s=n.getByCategory(o).length,i=ow[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(`
280
- `)}var at=class{discoveryCache=new Be;async resolve(e,t,o){return o.enabled?o.toolSearch?.enabled?this.resolveWithToolSearch(e,t,o):this.resolveLegacy(t,o):[]}getDiscoveryCache(){return this.discoveryCache}clearDiscoveryCache(){this.discoveryCache.clear()}resolveWithToolSearch(e,t,o){let r=[],s=new Set;r.push(it()),s.add(st);let i=o.toolSearch?.alwaysLoadedTools??[];for(let l of i){let p=t.get(l);p&&!s.has(l)&&(r.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)||(r.push(this.toSchema(p)),s.add(p.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let l=Be.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&&(r.push(this.toSchema(d)),s.add(m))}}return r}resolveLegacy(e,t){let o;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)o=e.getEnabled();else{let r=e.getByNames(t.enabledTools),s=e.getByCategories(t.enabledToolCategories),i=new Set;o=[];for(let a of[...r,...s])i.has(a.name)||(i.add(a.name),o.push(a))}return o.map(r=>this.toSchema(r))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};$o();c();function Oa(n){if(n.disabled)return"";let e=n.includeWorkingDirectory!==!1,t=n.includeToolCategories!==!1,o=e?`
281
- Working directory: ${n.workingDirectory}`:"",r=t&&n.toolCategories.length>0?`
282
- Available tool categories: ${n.toolCategories.join(", ")}`:"";return`You are an AI assistant with access to tools that let you interact with the user's system.${o}${r}
391
+ After discovering tools, you can call them directly by name.`,parameters:{type:"object",properties:{query:{type:"string",description:'Natural language search query (e.g., "read files", "web scraping", "execute shell commands")'},category:{type:"string",description:"Optional: filter by category",enum:["filesystem","network","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}};function Tt(){return{name:tt.name,displayName:tt.displayName,description:tt.description,parameters:tt.parameters,category:tt.category}}function un(r){return r===wt}l();var ET={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 hr(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=ET[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 xt=class{discoveryCache=new et;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(Tt()),s.add(wt);let i=o.toolSearch?.alwaysLoadedTools??[];for(let c of i){let p=t.get(c);p&&!s.has(c)&&(n.push(this.toSchema(p)),s.add(c))}let a=o.toolSearch?.alwaysLoadedCategories??[];for(let c of a)for(let p of t.getByCategory(c))s.has(p.name)||(n.push(this.toSchema(p)),s.add(p.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let c=et.fromMessages(e);this.discoveryCache.merge(c);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let u=t.get(m);u&&!s.has(m)&&u.cacheable!==!1&&(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}}};fn();l();function bl(r){if(r.disabled)return"";let e=r.includeWorkingDirectory!==!1,t=r.includeToolCategories!==!1,o=e?`
393
+ Working directory: ${r.workingDirectory}`:"",n=t&&r.toolCategories.length>0?`
394
+ Available tool categories: ${r.toolCategories.join(", ")}`:"";return`You are an AI assistant with access to tools that let you interact with the user's system.${o}${n}
283
395
 
284
396
  When the user asks you to do something, be proactive:
285
397
  - Use your tools to find information rather than asking the user for details you can discover yourself
286
398
  - Read files, list directories, and explore the codebase when asked to analyze or understand a project
287
- - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}c();var lt=class{analyticalPatterns=[/\b(analyze|find|search|check|list|show)\b/i,/\b(biggest|largest|smallest|most|least|all|every|count)\b/i,/\b(explain|understand|review|audit|inspect|examine)\b/i,/\b(compare|difference|similar|match|pattern)\b/i,/\b(what|where|how many|which|who|when|why|how)\b/i,/\?$/];actionPatterns=[/\b(create|write|update|modify|edit|patch|delete|remove|rename|move|copy)\b/i,/\b(run|execute|start|stop|restart|deploy|install|build)\b/i,/\b(fix|refactor|implement|add|change|replace|insert)\b/i,/\b(make|do|set|configure|setup|initialize)\b/i];classify(e){if(!e||e.trim().length===0)return{type:"conversational",confidence:0};let t=e.toLowerCase(),o=this.analyticalPatterns.filter(a=>a.test(t)).length,r=this.actionPatterns.filter(a=>a.test(t)).length,s=o/this.analyticalPatterns.length,i=r/this.actionPatterns.length;if(o>r&&o>0){let a=Math.min(s,1);return r>0&&(a=Math.min(a,.5)),{type:"analytical",confidence:a,reasoning:`Matched ${o} analytical patterns${r>0?`, ${r} action patterns (capped confidence)`:""}`}}else return r>o&&r>0?{type:"action",confidence:Math.min(i,1),reasoning:`Matched ${r} action patterns`}:o===r&&o>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${o} analytical, ${r} action patterns)`}:{type:"conversational",confidence:.3,reasoning:"No strong analytical or action patterns detected"}}getToolRoundsAdjustment(e,t){return e.type==="analytical"&&e.confidence>.6?Math.min(t+3,10):(e.type==="action"&&e.confidence>.6,t)}};c();var _r=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let r=e[o],s=[],i=JSON.stringify(r.arguments).toLowerCase();for(let a=0;a<o;a++){let l=e[a];this.hasDependency(r,l,i)&&s.push(l.id)}t.push({toolCallId:r.id,dependsOn:s})}return t}hasDependency(e,t,o){return!!(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&o.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&o.includes(t.arguments.url.toLowerCase()))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let r=this.analyzeDependencies(e),s=new Map,i=new Set;for(;i.size<e.length;){let a=[];for(let p of e){if(i.has(p.id))continue;(r.find(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 r=[];if(e.length<=o){let s=e.map(async i=>{let a=await t(i);return{id:i.id,result:a}});return await Promise.all(s)}for(let s=0;s<e.length;s+=o){let a=e.slice(s,s+o).map(async p=>{let m=await t(p);return{id:p.id,result:m}}),l=await Promise.all(a);r.push(...l)}return r}shouldUseParallelExecution(e){return e.length<2?!1:this.analyzeDependencies(e).filter(r=>r.dependsOn.length===0).length>=2}};c();function He(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(t?.role!=="user")continue;let o=t?.content;return typeof o=="string"?o:Array.isArray(o)?o.map(r=>r?.type==="text"?r.text:"").filter(Boolean).join(`
288
- `):""}return""}P();var Fa=0;function ds(){return Fa+=1,`${Date.now()}-${Fa}`}function Er(n,e){Ke("debug")&&(h(`[AIClient][${n}] Messages (${e.length}):`),e.forEach((t,o)=>{let r=O(t.content,300);h(`[AIClient][${n}] #${o} role=${t.role} content=${r}`)}))}function qa(n){let e=He(n).toLowerCase();return e?[/\b(list|show|print|display)\b.*\b(files|folders|directory|dir)\b/,/\b(current|this)\b.*\b(directory|folder|repo|repository)\b/,/\b(read|open|view)\b.*\b(file|log|config|json|yaml|env)\b/,/\b(write|create|update|modify|edit|patch|delete|remove|rename|move|copy)\b.*\b(file|folder|directory)\b/,/\b(run|execute)\b.*\b(command|shell|script|tests?)\b/,/\b(http|get|post|put|delete|download|fetch|curl)\b/,/\b(web|search|scrape|crawl|map)\b/,/https?:\/\//].some(o=>o.test(e)):!1}function Wa(n,e){let t=-1;for(let r=n.length-1;r>=0;r--){let s=n[r];if(s.role==="tool"||s.role==="assistant"&&s.tool_calls&&s.tool_calls.length>0){t=r;break}}if(t===-1)return!1;let o=n.length-1-t;return o>0&&o<=e}function Ua(n){return{openai:"gpt-4.1-mini",anthropic:"claude-3-haiku-20240307",gemini:"gemini-2.0-flash-exp",ollama:"llama3.2"}[n]||"default"}function rw(n){let e=[],t=0;for(let o=n.length-1;o>=0&&t<2;o--){let r=n[o];if(r.role==="assistant"&&r.tool_calls&&r.tool_calls.length>0){t++;for(let s of r.tool_calls){let i=s.function?.name||"unknown",a=s.function?.arguments,l=`Tool: ${i}`;if(a)try{let p=typeof a=="string"?JSON.parse(a):a;p.url&&(l+=` (URL: ${p.url})`),p.file_path&&(l+=` (File: ${p.file_path})`),p.section&&(l+=` (Section: ${p.section})`),p.query&&(l+=` (Query: ${p.query})`),p.command&&(l+=` (Command: ${p.command.substring(0,50)})`)}catch{}e.push(l)}}}return e.length>0?e.join(", "):"None"}async function Ga(n,e,t,o){let r=ds();h(`[AIClient][${r}] inferNeedsToolsWithAI() provider=${e} model=${o}`);let s=rw(t),a=t.filter(p=>p.role==="user").slice(-1)[0]?.content||"",l=`Recent tool usage: ${s}
289
-
290
- User's new message: "${a}"
291
-
292
- Does this message:
293
- 1. Ask about the same topic/context as recent tools? OR
294
- 2. Request new information that requires external tools (web search, file access, commands)?
295
-
296
- If the message is general knowledge (math, definitions, explanations) or completely unrelated to recent tool context, answer NO.
297
- If it asks about the same context OR needs new external information, answer YES.
298
-
299
- Answer only: YES or NO`;try{let m=((await n.generate({model:o,messages:[{role:"user",content:l}],max_tokens:10,temperature:0})).content||"").trim().toUpperCase(),d=m.startsWith("YES");return h(`[AIClient][${r}] inferNeedsToolsWithAI() context="${s}" message="${a.substring(0,50)}" result=${d} (raw: ${m})`),d}catch(p){return M(`[AIClient][${r}] inferNeedsToolsWithAI() error=${p} - falling back to false`),!1}}function Ba(n){let e=He(n).toLowerCase();if(!e)return!1;let t=[/\b(list|show|print|display)\b.*\b(files|folders|directory|dir)\b/,/\b(current|this)\b.*\b(directory|folder|repo|repository)\b/,/\b(read|open|view)\b.*\b(file|log|config|json|yaml|env)\b/],o=[/\b(write|create|update|modify|edit|patch|delete|remove|rename|move|copy)\b/,/\b(run|execute)\b.*\b(command|shell|script|tests?)\b/,/\b(http|get|post|put|delete|download|fetch|curl)\b/,/\b(web|search|scrape|crawl)\b/];return t.some(r=>r.test(e))&&!o.some(r=>r.test(e))}var Mo=class extends za.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||V,this.toolRouter=new at,this.bm25Engine=new nt,this.queryClassifier=new lt,this.toolOrchestrator=new _r,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??V.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=cs(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,r=this.providerModelCache.get(o);if(!r){try{r=await e.getModels()}catch{r=[]}this.providerModelCache.set(o,r)}return r.find(s=>s.id===t||s.displayName===t)}async countRequestTokens(e,t,o){let r=await t.countTokens(e.messages,o);return typeof r=="number"&&Number.isFinite(r)?r:ts(e.messages,o,t.getDisplayName().toLowerCase())}async pruneConversation(e,t,o){let r=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=ns(s.messages,l,r),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,r=[];e.messages.forEach((l,p)=>{o&&l.role==="system"||l.role!=="tool"&&r.push(p)});let s=Math.max(0,e.messages.length-t);if(s===0)return e;let i=new Set(r.slice(0,s)),a=e.messages.filter((l,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,r=o.filter(T=>T.role==="system"),s=o.filter(T=>T.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=as(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 ko("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let d=await this.countRequestTokens({...e,messages:a},t,l),f=ls(m.content,a,d),b=is(f);if(!b.valid)throw new ko(`Summarization result is invalid: ${b.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",m.content);let y=kr(f.summary,a.length),w=[...r,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),r=await this.getModelInfo(t,o.model),s=r?.contextWindow??1e5,i=o.max_tokens??r?.maxOutputTokens??1024,a=this.contextWindowConfig.outputTokenBuffer??1.15,l=os(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 So("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 So("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 r=t.bypass??{};return!!(r.tools?.includes(e.name)||r.categories?.includes(e.category)||e.confirmation&&r.levels?.includes(e.confirmation.level))}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new 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,C(`[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()),C(`[AIClient] Re-indexed ${this.bm25Engine.getIndexedCount()} tools for BM25 search`))}clearToolDiscoveryCache(){this.toolRouter.clearDiscoveryCache()}async generate(e,t){let o=this.getProvider(t);try{let r=ds(),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=qa(l.messages),y=this.toolsConfig.intelligentToolDetection,w=!1;if(!b&&y?.enabled&&d&&Wa(l.messages,y.maxFollowUpMessages)){C(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let _=Ua(i||"openai");b=await Ga(o,i||"openai",l.messages,_),w=!0}let T=Ba(l.messages);!f&&d&&(m==="required"||m==="required_for_actions"&&b)?l.tool_choice="required":!f&&d&&w&&!b&&(l.tool_choice="none",C(`[AIClient][${r}] AI inference determined no tools needed, setting tool_choice=none`));let D=o?.constructor?.name||"UnknownProvider",F={...this.stripRequestTools(l),__toolpack_request_id:r};C(`[AIClient][${r}] generate() start provider=${i} class=${D} 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}`),Er(r,l.messages);let k=await o.generate(F);if(h(`[AIClient][${r}] generate() initial response finish_reason=${k.finish_reason??"unknown"} tool_calls=${k.tool_calls?.length||0} content_preview=${O(k.content||"",200)}`),this.toolsConfig.autoExecute&&(this.toolRegistry||p.size>0)){let $=He(l.messages),_=this.queryClassifier.classify($),E=this.toolsConfig.maxToolRounds,U=this.queryClassifier.getToolRoundsAdjustment(_,E);U!==E?C(`[AIClient][${r}] Query classified as ${_.type} (confidence: ${_.confidence.toFixed(2)}), adjusted maxToolRounds: ${E} \u2192 ${U}`):h(`[AIClient][${r}] Query classified as ${_.type} (confidence: ${_.confidence.toFixed(2)}), keeping maxToolRounds: ${U}`);let Y=0,H=[...l.messages];for(k.tool_calls&&k.tool_calls.length>0&&C(`[AIClient] Received ${k.tool_calls.length} tool call(s): ${k.tool_calls.map(Q=>Q.name).join(", ")}`);k.tool_calls&&k.tool_calls.length>0&&Y<U;){Y++,this.currentRound=Y,C(`[AIClient][${r}] generate() tool round ${Y}/${U} tool_calls=${k.tool_calls.length}`),H.push({role:"assistant",content:k.content||"",tool_calls:k.tool_calls.map(K=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments)}}))});let Q=this.toolOrchestrator.shouldUseParallelExecution(k.tool_calls),We=3,Re=k.tool_calls,ae=k.tool_calls.filter(K=>K.name==="web.fetch");if(ae.length>We){C(`[AIClient][${r}] Limiting web.fetch calls from ${ae.length} \u2192 ${We} to prevent context overflow`);let K=ae.slice(0,We);Re=[...k.tool_calls.filter(R=>R.name!=="web.fetch"),...K];let q=ae.slice(We);for(let R of q)H.push({role:"tool",tool_call_id:R.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let le=5e4,xe=0;if(Q){C(`[AIClient][${r}] Using parallel execution for ${Re.length} tools`);let K=await this.toolOrchestrator.executeWithDependencies(Re,q=>this.executeTool(q,p),5),ce=!1;for(let q of Re){if(ce){H.push({role:"tool",tool_call_id:q.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let R=K.get(q.id),pe=typeof R=="string"?R:JSON.stringify(R);if(xe+pe.length>le){M(`[AIClient][${r}] Tool output budget exceeded (${le} chars), adding placeholder for remaining tools`),H.push({role:"tool",tool_call_id:q.id,content:"[Skipped: tool output budget exceeded for this round]"}),ce=!0;continue}let me=typeof R=="string"&&R.length>this.toolResultMaxChars?`${R.slice(0,this.toolResultMaxChars)}
300
- [TRUNCATED tool result: ${R.length} chars]`:R,Ue=typeof me=="string"?me:JSON.stringify(me);xe+=Ue.length,H.push({role:"tool",tool_call_id:q.id,content:me})}h(`[AIClient][${r}] Round tool output size: ${xe} chars (budget: ${le})`)}else{C(`[AIClient][${r}] Using sequential execution for ${Re.length} tools`);let K=!1;for(let ce of Re){if(K){H.push({role:"tool",tool_call_id:ce.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let q=await this.executeTool(ce,p),R=typeof q=="string"?q:JSON.stringify(q);if(xe+R.length>le){M(`[AIClient][${r}] Tool output budget exceeded (${le} chars), adding placeholder for remaining tools`),H.push({role:"tool",tool_call_id:ce.id,content:"[Skipped: tool output budget exceeded for this round]"}),K=!0;continue}let pe=typeof q=="string"&&q.length>this.toolResultMaxChars?`${q.slice(0,this.toolResultMaxChars)}
301
- [TRUNCATED tool result: ${q.length} chars]`:q,me=typeof pe=="string"?pe:JSON.stringify(pe);xe+=me.length,H.push({role:"tool",tool_call_id:ce.id,content:pe})}h(`[AIClient][${r}] Round tool output size: ${xe} chars (budget: ${le})`)}let ot={...l,messages:H,__toolpack_request_id:r},ge=this.stripRequestTools((await this.enrichRequestWithTools(ot)).request);ge=await this.enforceContextWindow(ge,o),ge.tool_choice==="required"&&(ge.tool_choice=T?"none":"auto",C(`[AIClient][${r}] generate() followup tool_choice override required->${ge.tool_choice}`)),Ke("debug")&&(h(`[AIClient][${r}] generate() followup request messages=${H.length}`),Er(r,H)),k=await o.generate(ge),h(`[AIClient][${r}] generate() followup response finish_reason=${k.finish_reason??"unknown"} tool_calls=${k.tool_calls?.length||0} content_preview=${O(k.content||"",200)}`)}}return k}catch(r){throw this.wrapError(r)}}async*stream(e,t){let o=this.getProvider(t);try{let r=ds(),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=qa(l.messages),y=this.toolsConfig.intelligentToolDetection,w=!1;if(!b&&y?.enabled&&d&&Wa(l.messages,y.maxFollowUpMessages)){C(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let Q=Ua(s||"openai");b=await Ga(o,s||"openai",l.messages,Q),w=!0}let T=Ba(l.messages);!f&&d&&(m==="required"||m==="required_for_actions"&&b)?l.tool_choice="required":!f&&d&&w&&!b&&(l.tool_choice="none",C(`[AIClient][${r}] AI inference determined no tools needed, setting tool_choice=none`));let D=o?.constructor?.name||"UnknownProvider",F={...this.stripRequestTools(l),__toolpack_request_id:r};if(C(`[AIClient][${r}] stream() start provider=${s} class=${D} 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}`),Er(r,l.messages),!this.toolsConfig.autoExecute||!this.toolRegistry&&p.size===0){yield*o.stream(F);return}let k=[...l.messages],$=0,_=He(l.messages),E=this.queryClassifier.classify(_),U=this.toolsConfig.maxToolRounds,Y=this.queryClassifier.getToolRoundsAdjustment(E,U);for(Y!==U&&C(`[AIClient][${r}] stream() Query classified as ${E.type} (confidence: ${E.confidence.toFixed(2)}), adjusted maxToolRounds: ${U} \u2192 ${Y}`);$<=Y;){if(e.signal?.aborted){C(`[AIClient][${r}] stream() aborted by signal`);return}let H="",Q=[];$++,this.currentRound=$,C(`[AIClient][${r}] stream() round_start ${$}/${Y}`);let We=null,Re={...l,messages:k},ae=this.stripRequestTools((await this.enrichRequestWithTools(Re)).request);ae=await this.enforceContextWindow(ae,o),$>0&&ae.tool_choice==="required"&&(ae.tool_choice=T?"none":"auto",C(`[AIClient][${r}] stream() round_${$+1} tool_choice override required->${ae.tool_choice}`));for await(let R of o.stream(ae)){if(e.signal?.aborted){C(`[AIClient][${r}] stream() aborted by signal during chunk processing`);return}R.tool_calls&&R.tool_calls.length>0&&(Q.push(...R.tool_calls),h(`[AIClient][${r}] stream() tool_calls_chunk count=${R.tool_calls.length} names=${R.tool_calls.map(pe=>pe.name).join(", ")}`),yield R),R.delta&&(H+=R.delta,yield R),R.finish_reason&&(We=R.finish_reason),R.finish_reason==="stop"&&(yield R)}if(h(`[AIClient][${r}] stream() round_end finish_reason=${We??"unknown"} accumulated_len=${H.length} tool_calls_total=${Q.length} content_preview=${O(H,200)}`),Q.length===0)break;if(C(`[AIClient][${r}] stream() received ${Q.length} tool call(s): ${Q.map(R=>R.name).join(", ")}`),$++,$>Y){C(`[AIClient][${r}] stream() max tool rounds (${Y}) reached`);break}C(`[AIClient][${r}] stream() tool round ${$}/${Y}`),k.push({role:"assistant",content:H||"",tool_calls:Q.map(R=>({id:R.id,type:"function",function:{name:R.name,arguments:JSON.stringify(R.arguments)}}))});let le=3,xe=Q,ot=Q.filter(R=>R.name==="web.fetch");if(ot.length>le){C(`[AIClient][${r}] Limiting web.fetch calls from ${ot.length} \u2192 ${le} to prevent context overflow`);let R=ot.slice(0,le);xe=[...Q.filter(Ue=>Ue.name!=="web.fetch"),...R];let me=ot.slice(le);for(let Ue of me)k.push({role:"tool",tool_call_id:Ue.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ge=5e4,K=0,ce=!1,q=[];for(let R of xe){if(ce){k.push({role:"tool",tool_call_id:R.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let pe=Date.now(),me=!1,Ue=setInterval(()=>{me||q.push({delta:""})},500),$e=await this.executeTool(R,p);me=!0,clearInterval(Ue);let $b=Date.now()-pe;for(;q.length>0;)yield q.shift();await new Promise(Db=>setTimeout(Db,0));let _b=typeof $e=="string"?$e:JSON.stringify($e);if(K+_b.length>ge){M(`[AIClient][${r}] Tool output budget exceeded (${ge} chars), adding placeholder for remaining tools`),k.push({role:"tool",tool_call_id:R.id,content:"[Skipped: tool output budget exceeded for this round]"}),ce=!0;continue}let Ge=typeof $e=="string"&&$e.length>this.toolResultMaxChars?`${$e.slice(0,this.toolResultMaxChars)}
302
- [TRUNCATED tool result: ${$e.length} chars]`:$e,Eb=typeof Ge=="string"?Ge:JSON.stringify(Ge);K+=Eb.length,k.push({role:"tool",tool_call_id:R.id,content:Ge}),yield{delta:"",tool_calls:[{...R,result:typeof Ge=="string"?Ge:JSON.stringify(Ge),duration:$b}]}}h(`[AIClient][${r}] Round tool output size: ${K} chars (budget: ${ge})`),Ke("debug")&&(h(`[AIClient][${r}] stream() after_tools messages=${k.length}`),Er(r,k))}}catch(r){throw this.wrapError(r)}}async embed(e,t){let o=this.getProvider(t);try{return await o.embed(e)}catch(r){throw this.wrapError(r)}}async enrichRequestWithTools(e){if(this.activeMode?.blockAllTools)return C(`[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)),r=t.size>0;if(!this.toolsConfig.enabled&&!r)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&&C(`[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&&C(`[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 r of e)o.set(r.name,r);for(let r of t)o.set(r.name,r);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 r of e)o.set(r.function.name,r);for(let r of t)o.set(r.function.name,r);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 r="<!-- 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(`
303
- `))}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=`${r}
399
+ - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}l();var vt=class{analyticalPatterns=[/\b(analyze|find|search|check|list|show)\b/i,/\b(biggest|largest|smallest|most|least|all|every|count)\b/i,/\b(explain|understand|review|audit|inspect|examine)\b/i,/\b(compare|difference|similar|match|pattern)\b/i,/\b(what|where|how many|which|who|when|why|how)\b/i,/\?$/];actionPatterns=[/\b(create|write|update|modify|edit|patch|delete|remove|rename|move|copy)\b/i,/\b(run|execute|start|stop|restart|deploy|install|build)\b/i,/\b(fix|refactor|implement|add|change|replace|insert)\b/i,/\b(make|do|set|configure|setup|initialize)\b/i];classify(e){if(!e||e.trim().length===0)return{type:"conversational",confidence:0};let t=e.toLowerCase(),o=this.analyticalPatterns.filter(a=>a.test(t)).length,n=this.actionPatterns.filter(a=>a.test(t)).length,s=o/this.analyticalPatterns.length,i=n/this.actionPatterns.length;if(o>n&&o>0){let a=Math.min(s,1);return n>0&&(a=Math.min(a,.5)),{type:"analytical",confidence:a,reasoning:`Matched ${o} analytical patterns${n>0?`, ${n} action patterns (capped confidence)`:""}`}}else return n>o&&n>0?{type:"action",confidence:Math.min(i,1),reasoning:`Matched ${n} action patterns`}:o===n&&o>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${o} analytical, ${n} action patterns)`}:{type:"conversational",confidence:.3,reasoning:"No strong analytical or action patterns detected"}}getToolRoundsAdjustment(e,t){return e.type==="analytical"&&e.confidence>.6?Math.min(t+3,10):(e.type==="action"&&e.confidence>.6,t)}};l();var yr=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let n=e[o],s=[],i=JSON.stringify(n.arguments).toLowerCase();for(let a=0;a<o;a++){let c=e[a];this.hasDependency(n,c,i)&&s.push(c.id)}t.push({toolCallId:n.id,dependsOn:s})}return t}hasDependency(e,t,o){if(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&o.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&o.includes(t.arguments.url.toLowerCase()))return!0;let s=["github.pr.files.list","github.pr.diff.get","github.contents.getText"];if(["github.pr.reviews.submit","github.pr.reviewComments.reply"].includes(e.name)&&s.includes(t.name)||e.name==="github.contents.getText"&&t.name==="github.pr.files.list"||e.name==="github.pr.reviewThreads.resolve"&&t.name==="github.pr.reviewThreads.list")return!0;let a=["slack.conversations.history","slack.conversations.replies"];return!!(["slack.chat.postMessage","slack.chat.postEphemeral"].includes(e.name)&&a.includes(t.name)||e.name==="slack.reactions.add"&&a.includes(t.name))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let n=this.analyzeDependencies(e),s=new Map,i=new Set;for(;i.size<e.length;){let a=[];for(let p of e){if(i.has(p.id))continue;(n.find(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 c=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:m}of c)s.set(p,m),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let n=[];if(e.length<=o){let s=e.map(async i=>{let a=await t(i);return{id:i.id,result:a}});return await Promise.all(s)}for(let s=0;s<e.length;s+=o){let a=e.slice(s,s+o).map(async p=>{let m=await t(p);return{id:p.id,result:m}}),c=await Promise.all(a);n.push(...c)}return n}shouldUseParallelExecution(e){return e.length>=2}};l();function ot(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 vl=0;function Cl(){return vl+=1,`${Date.now()}-${vl}`}function br(r,e){nt("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 kl(r){let e=ot(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 Pl(r){let e=ot(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 bn=class extends Sl.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||Z,this.toolRouter=new xt,this.bm25Engine=new bt,this.queryClassifier=new vt,this.toolOrchestrator=new yr,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??Z.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.hitlConfig=e.hitlConfig,this.onToolConfirm=e.onToolConfirm,this.conversationId=e.conversationId,this.contextWindowConfig=e.contextWindowConfig,this.providerModelCache=new Map,this.contextWindowConfig&&this.contextWindowConfig.enabled!==!1&&(this.contextWindowStateManager=Ns(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:Ss(e.messages,o,t.getDisplayName().toLowerCase())}async pruneConversation(e,t,o){let n=this.contextWindowConfig?.retainSystemMessages??!0,s=e;for(let i=0;i<3;i+=1){let a=await this.countRequestTokens(s,t,s.model);if(a<=o)return s;let c=a-o,p=$s(s.messages,c,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((c,p)=>{o&&c.role==="system"||c.role!=="tool"&&n.push(p)});let s=Math.max(0,e.messages.length-t);if(s===0)return e;let i=new Set(n.slice(0,s)),a=e.messages.filter((c,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,n=o.filter(v=>v.role==="system"),s=o.filter(v=>v.role!=="system");if(s.length<4)return e;let i=s.slice(-4),a=s.slice(0,-4);if(a.length<2)return e;let c=this.contextWindowConfig?.summarizerModel||e.model,p=Ms(a,{model:c,maxSummaryTokens:500}),m=await t.generate({model:c,messages:p,max_tokens:500,temperature:0,response_format:"text"});if(!m.content)throw new dn("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let u=await this.countRequestTokens({...e,messages:a},t,c),f=Os(m.content,a,u),b=Ds(f);if(!b.valid)throw new dn(`Summarization result is invalid: ${b.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",m.content);let y=fr(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,c=Rs(i,a),p=Math.max(0,s-c),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 mn("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 mn("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,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=Cl(),s=this.injectBaseAgentContext(e);s=this.injectOverrideSystemPrompt(s),s=this.injectModeSystemPrompt(s);let i=t||this.defaultProvider,a=await this.enrichRequestWithTools(s),c=a.request,p=a.requestToolMap;c=await this.enforceContextWindow(c,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",u=(c.tools?.length||0)>0,f=c.tool_choice!=null,b=kl(c.messages),y=Pl(c.messages);!f&&u&&(m==="required"||m==="required_for_actions"&&b)&&(c.tool_choice="required");let v=o?.constructor?.name||"UnknownProvider",C={...this.stripRequestTools(c),__toolpack_request_id:n};P(`[AIClient][${n}] generate() start provider=${i} class=${v} model=${c.model} messages=${c.messages.length} tools=${c.tools?.length||0} tool_choice=${c.tool_choice??"unset"} policy=${m} needsTools=${b} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),br(n,c.messages);let T=await o.generate(C);if(h(`[AIClient][${n}] generate() initial response finish_reason=${T.finish_reason??"unknown"} tool_calls=${T.tool_calls?.length||0} content_preview=${O(T.content||"",200)}`),this.toolsConfig.autoExecute&&(this.toolRegistry||p.size>0)){let R=ot(c.messages),D=this.queryClassifier.classify(R),M=this.toolsConfig.maxToolRounds,S=c.maxToolRounds!==void 0?c.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(D,M);c.maxToolRounds!==void 0?h(`[AIClient][${n}] maxToolRounds overridden per-request: ${S} (classifier bypassed)`):S!==M?P(`[AIClient][${n}] Query classified as ${D.type} (confidence: ${D.confidence.toFixed(2)}), adjusted maxToolRounds: ${M} \u2192 ${S}`):h(`[AIClient][${n}] Query classified as ${D.type} (confidence: ${D.confidence.toFixed(2)}), keeping maxToolRounds: ${S}`);let $=0,_=[...c.messages];for(T.tool_calls&&T.tool_calls.length>0&&P(`[AIClient] Received ${T.tool_calls.length} tool call(s): ${T.tool_calls.map(j=>j.name).join(", ")}`);T.tool_calls&&T.tool_calls.length>0&&$<S;){$++,this.currentRound=$,P(`[AIClient][${n}] generate() tool round ${$}/${S} tool_calls=${T.tool_calls.length}`),_.push({role:"assistant",content:T.content||"",tool_calls:T.tool_calls.map(K=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments)}}))});let j=this.toolOrchestrator.shouldUseParallelExecution(T.tool_calls),Ee=3,Ae=T.tool_calls,he=T.tool_calls.filter(K=>K.name==="web.fetch");if(he.length>Ee){P(`[AIClient][${n}] Limiting web.fetch calls from ${he.length} \u2192 ${Ee} to prevent context overflow`);let K=he.slice(0,Ee);Ae=[...T.tool_calls.filter(be=>be.name!=="web.fetch"),...K];let V=he.slice(Ee);for(let be of V)_.push({role:"tool",tool_call_id:be.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let le=5e4,Y=0;if(j){P(`[AIClient][${n}] Using parallel execution for ${Ae.length} tools`);let K=await this.toolOrchestrator.executeWithDependencies(Ae,J=>this.executeTool(J,p),5);for(let J of Ae){let V=K.get(J.id),be=typeof V=="string"?V:JSON.stringify(V),we=le-Y,ne;Y+be.length>le?(L(`[AIClient][${n}] Tool output budget exceeded (${le} chars)`),ne=this.budgetTruncate(be,we)):typeof V=="string"&&V.length>this.toolResultMaxChars?ne=`${V.slice(0,this.toolResultMaxChars)}
401
+ [TRUNCATED tool result: ${V.length} chars]`:ne=be;let Ye=typeof ne=="string"?ne:JSON.stringify(ne);Y+=Ye.length,_.push({role:"tool",tool_call_id:J.id,content:ne})}h(`[AIClient][${n}] Round tool output size: ${Y} chars (budget: ${le})`)}else{P(`[AIClient][${n}] Using sequential execution for ${Ae.length} tools`);for(let K of Ae){let J=await this.executeTool(K,p),V=typeof J=="string"?J:JSON.stringify(J),be=le-Y,we;Y+V.length>le?(L(`[AIClient][${n}] Tool output budget exceeded (${le} chars)`),we=this.budgetTruncate(V,be)):typeof J=="string"&&J.length>this.toolResultMaxChars?we=`${J.slice(0,this.toolResultMaxChars)}
402
+ [TRUNCATED tool result: ${J.length} chars]`:we=V;let ne=typeof we=="string"?we:JSON.stringify(we);Y+=ne.length,_.push({role:"tool",tool_call_id:K.id,content:we})}h(`[AIClient][${n}] Round tool output size: ${Y} chars (budget: ${le})`)}let ht={...c,messages:_,__toolpack_request_id:n},ye=this.stripRequestTools((await this.enrichRequestWithTools(ht)).request);ye=await this.enforceContextWindow(ye,o),ye.tool_choice==="required"&&(ye.tool_choice=y?"none":"auto",P(`[AIClient][${n}] generate() followup tool_choice override required->${ye.tool_choice}`)),nt("debug")&&(h(`[AIClient][${n}] generate() followup request messages=${_.length}`),br(n,_)),T=await o.generate(ye),h(`[AIClient][${n}] generate() followup response finish_reason=${T.finish_reason??"unknown"} tool_calls=${T.tool_calls?.length||0} content_preview=${O(T.content||"",200)}`)}}return T}catch(n){throw this.wrapError(n)}}async*stream(e,t){let o=this.getProvider(t);try{let n=Cl(),s=t||this.defaultProvider,i=this.injectBaseAgentContext(e);i=this.injectOverrideSystemPrompt(i),i=this.injectModeSystemPrompt(i);let a=await this.enrichRequestWithTools(i),c=a.request,p=a.requestToolMap;c=await this.enforceContextWindow(c,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",u=(c.tools?.length||0)>0,f=c.tool_choice!=null,b=kl(c.messages),y=Pl(c.messages);!f&&u&&(m==="required"||m==="required_for_actions"&&b)&&(c.tool_choice="required");let v=o?.constructor?.name||"UnknownProvider",C={...this.stripRequestTools(c),__toolpack_request_id:n};if(P(`[AIClient][${n}] stream() start provider=${s} class=${v} model=${c.model} messages=${c.messages.length} tools=${c.tools?.length||0} tool_choice=${c.tool_choice??"unset"} policy=${m} needsTools=${b} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),br(n,c.messages),!this.toolsConfig.autoExecute||!this.toolRegistry&&p.size===0){yield*o.stream(C);return}let T=[...c.messages],R=0,D=ot(c.messages),M=this.queryClassifier.classify(D),S=this.toolsConfig.maxToolRounds,$=c.maxToolRounds!==void 0?c.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(M,S);for(c.maxToolRounds!==void 0?h(`[AIClient][${n}] stream() maxToolRounds overridden per-request: ${$} (classifier bypassed)`):$!==S&&P(`[AIClient][${n}] stream() Query classified as ${M.type} (confidence: ${M.confidence.toFixed(2)}), adjusted maxToolRounds: ${S} \u2192 ${$}`);R<=$;){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal`);return}let _="",j=[];R++,this.currentRound=R,P(`[AIClient][${n}] stream() round_start ${R}/${$}`);let Ee=null,Ae={...c,messages:T},he=this.stripRequestTools((await this.enrichRequestWithTools(Ae)).request);he=await this.enforceContextWindow(he,o),R>1&&he.tool_choice==="required"&&(he.tool_choice=y?"none":"auto",P(`[AIClient][${n}] stream() round_${R} tool_choice override required->${he.tool_choice}`));for await(let E of o.stream(he)){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal during chunk processing`);return}E.tool_calls&&E.tool_calls.length>0&&(j.push(...E.tool_calls),h(`[AIClient][${n}] stream() tool_calls_chunk count=${E.tool_calls.length} names=${E.tool_calls.map(re=>re.name).join(", ")}`),yield E),E.delta&&(_+=E.delta,yield E),E.finish_reason&&(Ee=E.finish_reason),E.finish_reason==="stop"&&(yield E)}if(h(`[AIClient][${n}] stream() round_end finish_reason=${Ee??"unknown"} accumulated_len=${_.length} tool_calls_total=${j.length} content_preview=${O(_,200)}`),j.length===0)break;P(`[AIClient][${n}] stream() received ${j.length} tool call(s): ${j.map(E=>E.name).join(", ")}`),P(`[AIClient][${n}] stream() tool round ${R}/${$}`),T.push({role:"assistant",content:_||"",tool_calls:j.map(E=>({id:E.id,type:"function",function:{name:E.name,arguments:JSON.stringify(E.arguments)}}))});let le=3,Y=j,ht=j.filter(E=>E.name==="web.fetch");if(ht.length>le){P(`[AIClient][${n}] Limiting web.fetch calls from ${ht.length} \u2192 ${le} to prevent context overflow`);let E=ht.slice(0,le);Y=[...j.filter(pn=>pn.name!=="web.fetch"),...E];let De=ht.slice(le);for(let pn of De)T.push({role:"tool",tool_call_id:pn.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ye=5e4,K=0,J=[],V=!1,be=setInterval(()=>{V||J.push({delta:""})},500),we=Date.now(),ne,Ye;try{if(Y.length>=2)P(`[AIClient][${n}] stream() using parallel execution for ${Y.length} tools`),Ye=new Map,ne=await this.toolOrchestrator.executeWithDependencies(Y,async E=>{let re=Date.now(),De=await this.executeTool(E,p);return Ye.set(E.id,Date.now()-re),De},5);else{P(`[AIClient][${n}] stream() executing single tool sequentially`),Ye=new Map,ne=new Map;for(let E of Y){let re=Date.now(),De=await this.executeTool(E,p);Ye.set(E.id,Date.now()-re),ne.set(E.id,De)}}}finally{V=!0,clearInterval(be)}for(;J.length>0;)yield J.shift();await new Promise(E=>setTimeout(E,0)),h(`[AIClient][${n}] stream() tool batch completed in ${Date.now()-we}ms`);for(let E of Y){let re=ne.get(E.id),De=typeof re=="string"?re:JSON.stringify(re),pn=ye-K,sT=Ye.get(E.id)??0,Ze;K+De.length>ye?(L(`[AIClient][${n}] Tool output budget exceeded (${ye} chars)`),Ze=this.budgetTruncate(De,pn)):typeof re=="string"&&re.length>this.toolResultMaxChars?Ze=`${re.slice(0,this.toolResultMaxChars)}
403
+ [TRUNCATED tool result: ${re.length} chars]`:Ze=De;let dl=typeof Ze=="string"?Ze:JSON.stringify(Ze);K+=dl.length,T.push({role:"tool",tool_call_id:E.id,content:Ze}),yield{delta:"",tool_calls:[{...E,result:dl,duration:sT}]}}h(`[AIClient][${n}] Round tool output size: ${K} chars (budget: ${ye})`),nt("debug")&&(h(`[AIClient][${n}] stream() after_tools messages=${T.length}`),br(n,T))}}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 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&&P(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${u} tools`)}let c=this.schemasToToolCallRequests(this.mergeSchemas(a,o));if(c.length===0)return{request:e,requestToolMap:t};let p={...e,tools:c};return this.toolsConfig.toolSearch?.enabled&&i&&(p=this.injectToolSearchPrompt(p)),{request:this.injectRequestToolGuidance(p,c),requestToolMap:t}}buildRequestToolMap(e){let t=new Map;for(let o of e||[])t.set(o.name,o);return t}requestToolToSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category,cacheable:e.cacheable}}mergeSchemas(e,t){let o=new Map;for(let n of e)o.set(n.name,n);for(let n of t)o.set(n.name,n);return Array.from(o.values())}schemasToToolCallRequests(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}))}mergeToolCallRequests(e,t){if(t.length===0)return e;let o=new Map;for(let n of e)o.set(n.function.name,n);for(let n of t)o.set(n.function.name,n);return Array.from(o.values())}injectRequestToolGuidance(e,t){let o=new Set((t||e.tools||[]).map(c=>c.function.name));if(o.size===0)return e;let n="<!-- TOOLPACK_REQUEST_TOOL_GUIDANCE -->",s=[];if(o.has("knowledge_search")||o.has("knowledge_add")){let c=["Knowledge Base:"];o.has("knowledge_search")&&c.push("- Use `knowledge_search` when you need factual or domain-specific information that may already be stored."),o.has("knowledge_add")&&c.push("- Use `knowledge_add` when you encounter a durable fact, user preference, or decision that future conversations should know. Do not add confidential information, routine task outputs, or context that is specific to this conversation only."),s.push(c.join(`
404
+ `))}if(o.has("conversation_search")&&s.push("Conversation History:\n- Only recent messages may be present in context.\n- Use `conversation_search` to find relevant details from earlier in this conversation when needed."),s.length===0)return e;let i=`${n}
304
405
  ${s.join(`
305
406
 
306
- `)}`,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(r)?p:{...p,content:`${d}
407
+ `)}`,a=e.messages.findIndex(c=>c.role==="system");if(a>=0){let c=e.messages.map((p,m)=>{if(m!==a)return p;let u=typeof p.content=="string"?p.content:"";return u.includes(n)?p:{...p,content:`${u}
307
408
 
308
- ${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(Ro(o.name)){let i=t.toolSearch?.enabled;if(i!==void 0?i:this.toolsConfig.toolSearch?.enabled??!1)return!0}let r=t.allowedTools.length>0,s=t.allowedToolCategories.length>0;if(r||s){let i=r&&t.allowedTools.includes(o.name),a=s&&t.allowedToolCategories.includes(o.category);return i||a}return!0})}injectModeSystemPrompt(e){if(!this.activeMode||!this.activeMode.systemPrompt)return h(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. activeMode=${this.activeMode?.name}, systemPrompt=${this.activeMode?.systemPrompt?.substring(0,50)}`),e;let t=this.activeMode.systemPrompt;if(h(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${this.activeMode.name}, length=${t.length}`),e.messages.some(r=>r.role==="system")){let r=e.messages.map(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
409
+ ${i}`.trim()}});return{...e,messages:c}}return{...e,messages:[{role:"system",content:i},...e.messages]}}stripRequestTools(e){let{requestTools:t,...o}=e;return o}filterSchemasByMode(e,t){return e.filter(o=>{if(t.blockedTools.includes(o.name)||t.blockedToolCategories.includes(o.category))return!1;if(un(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}
309
410
 
310
- ${t}`}}return s});return{...e,messages:r}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectOverrideSystemPrompt(e){if(!this.overrideSystemPrompt)return e;let t=this.overrideSystemPrompt;if(e.messages.some(r=>r.role==="system")){let r=e.messages.map(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
411
+ ${t}`}}return s});return{...e,messages:n}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectOverrideSystemPrompt(e){if(!this.overrideSystemPrompt)return e;let t=this.overrideSystemPrompt;if(e.messages.some(n=>n.role==="system")){let n=e.messages.map(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
311
412
 
312
- ${t}`}}return s});return{...e,messages:r}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectBaseAgentContext(e){let t=!0,o=!0,r,s=this.disableBaseContext;if(this.activeMode?.baseContext===!1)return e;this.activeMode?.baseContext&&(t=this.activeMode.baseContext.includeWorkingDirectory!==!1,o=this.activeMode.baseContext.includeToolCategories!==!1,r=this.activeMode.baseContext.custom);let i=r||Oa({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}
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||bl({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:s,includeWorkingDirectory:t,includeToolCategories:o});if(!i)return e;if(e.messages.some(c=>c.role==="system")){let c=e.messages.map(p=>{if(p.role==="system"){let m=typeof p.content=="string"?p.content:"";return{...p,content:`${i}
313
414
 
314
- ${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??[],r="";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(`
315
- `);i&&(r=`
415
+ ${m}`}}return p});return{...e,messages:c}}else return{...e,messages:[{role:"system",content:i},...e.messages]}}injectToolSearchPrompt(e){if(!this.toolRegistry)return e;let t=e.messages.some(i=>i.role==="system"),o=this.toolsConfig.toolSearch?.alwaysLoadedTools??[],n="";if(o.length>0){let i=o.map(a=>{let c=this.toolRegistry?.get(a);return c?` - **${c.name}**: ${c.description}`:null}).filter(Boolean).join(`
416
+ `);i&&(n=`
316
417
 
317
418
  You have these tools always available:
318
419
  ${i}
@@ -320,9 +421,9 @@ ${i}
320
421
  Use these tools directly when appropriate for the task.`)}let s=`
321
422
  IMPORTANT: Tool Discovery Instructions
322
423
 
323
- You have access to a limited set of tools. If you need a tool that is not in your current list, you MUST use the 'tool.search' tool to discover it.${r}
424
+ You have access to a limited set of tools. If you need a tool that is not in your current list, you MUST use the 'tool.search' tool to discover it.${n}
324
425
 
325
- ${$r(this.toolRegistry)}
426
+ ${hr(this.toolRegistry)}
326
427
 
327
428
  When you need a tool:
328
429
  1. Check if it's in your current tool list
@@ -330,35 +431,69 @@ When you need a tool:
330
431
  3. After discovering tools, you can call them directly in subsequent turns
331
432
 
332
433
  NEVER guess or hallucinate tool names. ALWAYS use tool.search to discover tools you don't have.
333
- `.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}
434
+ `.trim();if(t){let i=e.messages.map(a=>{if(a.role==="system"){let c=typeof a.content=="string"?a.content:"";return{...a,content:`${c}
334
435
 
335
- ${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}),C(`[AIClient] Executing tool: ${e.name} with args: ${O(e.arguments,500)}`);let r=t.get(e.name),s=r?void 0:this.toolRegistry?.get(e.name);if(!r&&!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(Ro(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=r||s;if(!i){M(`[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=>C(`[Tool] ${f}`)},p=r?await r.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 C(`[AIClient] Tool ${e.name} executed successfully in ${m}ms result_len=${d}`),Ke("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()}),oe(`[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 r=e.replace(/\./g,"_");if(t.some(l=>l.name===r))return r;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 r=0;r<=t.length;r++)o[r]=[r];for(let r=0;r<=e.length;r++)o[0][r]=r;for(let r=1;r<=t.length;r++)for(let s=1;s<=e.length;s++)t.charAt(r-1)===e.charAt(s-1)?o[r][s]=o[r-1][s-1]:o[r][s]=Math.min(o[r-1][s-1]+1,o[r][s-1]+1,o[r-1][s]+1);return o[t.length][e.length]}executeToolSearch(e){let{query:t,category:o}=e,r=this.toolsConfig.toolSearch?.searchResultLimit??5,s=typeof o=="string"&&o.length>0?o:void 0;if(this.activeMode&&!(this.filterSchemasByMode([it()],this.activeMode).length>0))return M("[AIClient] tool.search blocked by active mode"),JSON.stringify({query:t,found:0,tools:[],hint:"tool.search is not allowed in the current mode."});C(`[AIClient] Executing tool.search: query="${t}" category=${s||"all"} limit=${r}`);let i=this.activeMode?Math.max(r*4,r):r,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>r&&(a=a.slice(0,r));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 W(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};c();c();var bs=x(require("@anthropic-ai/sdk"),1);c();ne();var Z=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}};ne();P();var Ao=class extends Z{client;constructor(e,t){super(),this.client=new bs.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(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),r=o.system,s=o.userMessages,i={model:e.model,messages:s,system:r,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!1};e.tools&&e.tools.length>0?(i.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?i.tool_choice={type:"any"}:e.tool_choice==="none"?delete i.tools:i.tool_choice={type:"auto"},h(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&h(`[Anthropic][${t}] First tool: ${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"}`),se(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),r={model:e.model,messages:o.userMessages,system:o.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(r.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?r.tool_choice={type:"any"}:e.tool_choice==="none"?delete r.tools:r.tool_choice={type:"auto"},h(`[Anthropic][${t}] Sending ${r.tools?.length||0} tools with tool_choice: ${r.tool_choice?.type||"unset"}`),r.tools&&r.tools.length>0&&h(`[Anthropic][${t}] First tool: ${O(r.tools[0],800)}`)):h(`[Anthropic][${t}] NO TOOLS in request`),h(`[Anthropic][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice?.type??"unset"}`),se(t,"Anthropic",r.messages);let s=await this.client.messages.create(r,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"&&(De(`[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,r=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(pt(),No));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(`
336
- `);a&&(o=a)}}else if(i.role==="tool"&&i.tool_call_id)r.push({role:"user",content:[{type:"tool_result",tool_use_id:i.tool_call_id,content:typeof i.content=="string"?i.content:JSON.stringify(i.content)}]});else if(i.role==="assistant"&&i.tool_calls&&i.tool_calls.length>0){let a=[];if(typeof i.content=="string"&&i.content)a.push({type:"text",text:i.content});else if(Array.isArray(i.content)){let l=i.content.filter(p=>typeof p=="object"&&p.type==="text").map(p=>p.text).join(`
337
- `);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});r.push({role:"assistant",content:a})}else{let a=[];typeof i.content=="string"?a=i.content:i.content!==null&&(a=(await Promise.all(i.content.map(async 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)),r.push({role:i.role==="user"?"user":"assistant",content:a})}return{system:o,userMessages:r}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":e==="stop_sequence"?"stop":e}handleError(e){if(e instanceof bs.default.APIError){let t=e.message;return e.status===401?new ve(t,e):e.status===429?new Ce(t,void 0,e):e.status&&e.status>=400&&e.status<500?new I(t,e):new W(t,"ANTHROPIC_ERROR",e.status||500,e)}return new W("Unknown Anthropic error","UNKNOWN",500,e)}};c();var Va=require("@google/generative-ai");ne();P();var Oo=class extends Z{genAI;constructor(e){super(),this.genAI=new Va.GoogleGenerativeAI(e)}supportsFileUpload(){return!0}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[o,r]of Object.entries(e))o==="additionalProperties"||o==="exclusiveMinimum"||o==="exclusiveMaximum"||o==="$schema"||o==="$id"||o==="definitions"||o==="$defs"||(typeof r=="object"&&r!==null?Array.isArray(r)?t[o]=r.map(s=>this.sanitizeSchema(s)):t[o]=this.sanitizeSchema(r):t[o]=r);return t}async uploadFile(e){try{let t=await import("fs"),o=await import("path");if(!e.filePath)throw new I("Gemini uploadFile requires a filePath.");let r=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
436
+ ${s}`}}return a});return{...e,messages:i}}else return{...e,messages:[{role:"system",content:s},...e.messages]}}async executeTool(e,t){let o=Date.now();this.emit("tool:started",{toolName:e.name,toolCallId:e.id,status:"started",args:e.arguments}),P(`[AIClient] Executing tool: ${e.name} with args: ${O(e.arguments,500)}`);let n=t.get(e.name),s=n?void 0:this.toolRegistry?.get(e.name);if(!n&&!this.toolRegistry){let a="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:a,duration:Date.now()-o}),JSON.stringify({error:a})}if(un(e.name)){let a=this.executeToolSearch(e.arguments),c=Date.now()-o;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof a=="string"?a.substring(0,200):JSON.stringify(a).substring(0,200),duration:c}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:a,duration:c,status:"success",timestamp:Date.now()}),a}let i=n||s;if(!i){L(`[AIClient] Tool '${e.name}' not found in registry`);let a=this.findSimilarToolName(e.name),c=a?`Tool '${e.name}' not found. Did you mean '${a}'? Use tool.search to discover available tools.`:`Tool '${e.name}' not found. Use tool.search to discover available tools.`;return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:c,duration:Date.now()-o}),JSON.stringify({error:c})}try{let a=e.arguments;if(s?.confirmation&&this.onToolConfirm&&!this.isBypassed(s)){this.emit("tool:confirmation_requested",{tool:s,args:a,level:s.confirmation.level,reason:s.confirmation.reason});let 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 c={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:f=>P(`[Tool] ${f}`)},p=n?await n.execute(a):await i.execute(a,c),m=Date.now()-o;this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof p=="string"?p.substring(0,200):JSON.stringify(p).substring(0,200),duration:m}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:p,duration:m,status:"success",timestamp:Date.now()});let u=typeof p=="string"?p.length:JSON.stringify(p).length;return P(`[AIClient] Tool ${e.name} executed successfully in ${m}ms result_len=${u}`),nt("debug")&&h(`[AIClient] Tool ${e.name} result_preview=${O(p,400)}`),typeof p=="string"?p:JSON.stringify(p)}catch(a){let c=Date.now()-o,p=a.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:p,duration:c}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:p}),duration:c,status:"error",timestamp:Date.now()}),pe(`[AIClient] Tool ${e.name} failed: ${O(p,300)}`),JSON.stringify({error:p})}}findSimilarToolName(e){if(!this.toolRegistry)return null;let t=this.toolRegistry.getAll(),o=e.replace(/_/g,".");if(t.some(c=>c.name===o))return o;let n=e.replace(/\./g,"_");if(t.some(c=>c.name===n))return n;let s=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(c=>c.name===s))return s;let i=null,a=1/0;for(let c of t){let p=this.levenshteinDistance(e.toLowerCase(),c.name.toLowerCase());p<=2&&p<a&&(a=p,i=c.name)}return i}levenshteinDistance(e,t){let o=[];for(let n=0;n<=t.length;n++)o[n]=[n];for(let n=0;n<=e.length;n++)o[0][n]=n;for(let n=1;n<=t.length;n++)for(let s=1;s<=e.length;s++)t.charAt(n-1)===e.charAt(s-1)?o[n][s]=o[n-1][s-1]:o[n][s]=Math.min(o[n-1][s-1]+1,o[n][s-1]+1,o[n-1][s]+1);return o[t.length][e.length]}executeToolSearch(e){let{query:t,category:o}=e,n=this.toolsConfig.toolSearch?.searchResultLimit??5,s=typeof o=="string"&&o.length>0?o:void 0;if(this.activeMode&&!(this.filterSchemasByMode([Tt()],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)),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 c=a.map(p=>p.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,c),h(`[AIClient] tool.search found ${a.length} tools: ${c.join(", ")||"none"}`),JSON.stringify({query:t,found:a.length,tools:a.map(p=>({name:p.tool.name,displayName:p.tool.displayName,description:p.tool.description,category:p.tool.category,parameters:p.tool.parameters,relevanceScore:Math.round(p.score*100)/100})),hint:a.length>0?`Found ${a.length} tools. You can now call any of these tools directly.`:`No tools found for "${t}". Try a different search term.`})}wrapError(e){return e instanceof N?e:new F(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}budgetTruncate(e,t){let o=`
437
+ [Output truncated \u2014 round budget reached. Call the tool again with a narrower query to retrieve more.]`,s=t-o.length;return s>=100?e.slice(0,s)+o:"[Tool output omitted \u2014 round budget exhausted. Call the tool again with a narrower query.]"}};l();l();var Us=x(require("@anthropic-ai/sdk"),1);l();ce();var Q=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}};ce();k();var Tn=class extends Q{client;constructor(e,t){super(),this.client=new Us.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"}`),ee(t,"Anthropic",i.messages);let a=await this.client.messages.create(i,e.signal?{signal:e.signal}:void 0),c=[],p=[];for(let m of a.content)m.type==="text"?c.push(m.text):m.type==="tool_use"&&p.push({id:m.id,name:this.restoreToolName(m.name,e.tools),arguments:m.input});return h(`[Anthropic][${t}] Response finish_reason=${a.stop_reason} tool_calls=${p.length} content_preview=${O(c.join(""),200)}`),{content:c.length>0?c.join(""):null,usage:{prompt_tokens:a.usage.input_tokens,completion_tokens:a.usage.output_tokens,total_tokens:a.usage.input_tokens+a.usage.output_tokens},finish_reason:this.mapFinishReason(a.stop_reason),tool_calls:p.length>0?p:void 0,raw:a}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),n={model:e.model,messages:o.userMessages,system:o.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(n.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?n.tool_choice={type:"any"}:e.tool_choice==="none"?delete n.tools:n.tool_choice={type:"auto"},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"}`),ee(t,"Anthropic",n.messages);let s=await this.client.messages.create(n,e.signal?{signal:e.signal}:void 0),i="",a="",c="",p=!1;for await(let m of s)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,i=m.content_block.id,a=m.content_block.name,c=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(c+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(h(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${a}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:i,name:this.restoreToolName(a,e.tools),arguments:JSON.parse(c||"{}")}]},p=!1),m.type==="message_stop"&&(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(),wn));for(let i of e)if(i.role==="system"){if(typeof i.content=="string")o=i.content;else if(i.content!==null){let a=i.content.filter(c=>typeof c=="object"&&c.type==="text").map(c=>c.text).join(`
438
+ `);a&&(o=a)}}else if(i.role==="tool"&&i.tool_call_id)n.push({role:"user",content:[{type:"tool_result",tool_use_id:i.tool_call_id,content:typeof i.content=="string"?i.content:JSON.stringify(i.content)}]});else if(i.role==="assistant"&&i.tool_calls&&i.tool_calls.length>0){let a=[];if(typeof i.content=="string"&&i.content)a.push({type:"text",text:i.content});else if(Array.isArray(i.content)){let c=i.content.filter(p=>typeof p=="object"&&p.type==="text").map(p=>p.text).join(`
439
+ `);c&&a.push({type:"text",text:c})}for(let c of i.tool_calls)a.push({type:"tool_use",id:c.id,name:this.sanitizeToolName(c.function.name),input:typeof c.function.arguments=="string"?JSON.parse(c.function.arguments||"{}"):c.function.arguments});n.push({role:"assistant",content:a})}else{let a=[];typeof i.content=="string"?a=i.content:i.content!==null&&(a=(await Promise.all(i.content.map(async c=>{if(c.type==="text")return{type:"text",text:c.text};if(c.type==="image_url"){let p=c.image_url.url;if(p.startsWith("data:")){let m=p.match(/^data:(image\/\w+);base64,(.+)$/);if(m)return{type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}}return{type:"image",source:{type:"url",url:p}}}if(c.type==="image_data"||c.type==="image_file"){let{data:p,mimeType:m}=await s(c);return{type:"image",source:{type:"base64",media_type:m,data:p}}}return null}))).filter(Boolean)),n.push({role:i.role==="user"?"user":"assistant",content:a})}return{system:o,userMessages:n}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":e==="stop_sequence"?"stop":e}handleError(e){if(e instanceof Us.default.APIError){let t=e.message;return e.status===401?new de(t,e):e.status===429?new Te(t,void 0,e):e.status&&e.status>=400&&e.status<500?new I(t,e):new F(t,"ANTHROPIC_ERROR",e.status||500,e)}return new F("Unknown Anthropic error","UNKNOWN",500,e)}};l();var Dl=require("@google-cloud/vertexai");ce();k();var xn=class extends Q{vertexAI;location;constructor(e={}){super(),this.name="vertexai";let t=e.projectId??process.env.TOOLPACK_VERTEXAI_PROJECT??process.env.VERTEX_AI_PROJECT??process.env.GOOGLE_CLOUD_PROJECT;if(!t)throw new de("Vertex AI requires a GCP project ID. Pass projectId in config or set TOOLPACK_VERTEXAI_PROJECT / VERTEX_AI_PROJECT / GOOGLE_CLOUD_PROJECT.");this.location=e.location??process.env.TOOLPACK_VERTEXAI_LOCATION??process.env.VERTEX_AI_LOCATION??"us-central1",this.vertexAI=new Dl.VertexAI({project:t,location:this.location,googleAuthOptions:e.googleAuthOptions})}getDisplayName(){return"Google Vertex AI"}async getModels(){return[{id:"gemini-2.5-pro-preview-05-06",displayName:"Gemini 2.5 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.5-flash-preview-04-17",displayName:"Gemini 2.5 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.0-flash-001",displayName:"Gemini 2.0 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:8192},{id:"gemini-1.5-pro-002",displayName:"Gemini 1.5 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2097152,maxOutputTokens:8192},{id:"gemini-1.5-flash-002",displayName:"Gemini 1.5 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:8192}]}async generate(e){try{let t=e.__toolpack_request_id||`vtx-${Date.now()}`;h(`[VertexAI][${t}] generate() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),ee(t,"VertexAI",e.messages);let o=this.buildModel(e),{history:n,lastUserMessage:s}=this.formatHistory(e.messages),c=(await o.startChat({history:n}).sendMessage(s)).response,{content:p,toolCalls:m}=this.parseResponse(c,e.tools);return 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:c.usageMetadata?.promptTokenCount??0,completion_tokens:c.usageMetadata?.candidatesTokenCount??0,total_tokens:c.usageMetadata?.totalTokenCount??0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:c}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`vtx-str-${Date.now()}`;h(`[VertexAI][${t}] stream() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),ee(t,"VertexAI",e.messages);let o=this.buildModel(e),{history:n,lastUserMessage:s}=this.formatHistory(e.messages),a=await o.startChat({history:n}).sendMessageStream(s);for await(let c of a.stream)for(let p of c.candidates??[])for(let m of p.content?.parts??[])if(m.functionCall){let u=m.functionCall;h(`[VertexAI][${t}] stream tool_call name=${u.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:this.restoreToolName(u.name,e.tools),arguments:u.args??{}}]}}else m.text&&(yield{delta:m.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.")}buildModel(e){let t={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages),generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}};return e.tools&&e.tools.length>0&&(t.tools=[{functionDeclarations:e.tools.map(o=>({name:this.sanitizeToolName(o.function.name),description:o.function.description,parameters:this.sanitizeSchema(o.function.parameters)}))}]),this.vertexAI.getGenerativeModel(t)}formatHistory(e){let t=e.filter(i=>i.role!=="system");if(t.length===0)return{history:[],lastUserMessage:""};let o=t.slice(0,-1),n=t[t.length-1];return{history:o.map(i=>{if(i.role==="tool"&&i.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(i.name??i.tool_call_id),response:{name:this.sanitizeToolName(i.name??i.tool_call_id),content:typeof i.content=="string"?i.content:JSON.stringify(i.content)}}}]};if(i.role==="assistant"&&i.tool_calls&&i.tool_calls.length>0){let a=[];typeof i.content=="string"&&i.content&&a.push({text:i.content});for(let c of i.tool_calls)a.push({functionCall:{name:this.sanitizeToolName(c.function.name),args:typeof c.function.arguments=="string"?JSON.parse(c.function.arguments||"{}"):c.function.arguments}});return{role:"model",parts:a}}return{role:i.role==="user"?"user":"model",parts:this.contentToParts(i.content)}}),lastUserMessage:this.contentToParts(n.content)}}contentToParts(e){return typeof e=="string"?[{text:e}]:e?e.map(t=>t.type==="text"?{text:t.text}:t.type==="image_data"?{inlineData:{mimeType:t.mimeType??"image/jpeg",data:t.data}}:null).filter(t=>t!==null):[]}parseResponse(e,t){let o=[],n="";for(let s of e.candidates??[])for(let i of s.content?.parts??[])if(i.text&&(n+=i.text),i.functionCall){let a=i.functionCall;o.push({id:`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:this.restoreToolName(a.name,t),arguments:a.args??{}})}return{content:n,toolCalls:o}}extractSystemInstruction(e){let t=e.filter(o=>o.role==="system");if(t.length!==0)return t.map(o=>typeof o.content=="string"?o.content:"").join(`
440
+ `)}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name??e.replace(/_/g,".")}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[o,n]of Object.entries(e))["additionalProperties","exclusiveMinimum","exclusiveMaximum","$schema","$id","definitions","$defs"].includes(o)||(t[o]=typeof n=="object"&&n!==null?Array.isArray(n)?n.map(s=>this.sanitizeSchema(s)):this.sanitizeSchema(n):n);return t}handleError(e){let t=e?.message??String(e);return e?.status===429||t.includes("RESOURCE_EXHAUSTED")?new Te(t,void 0,e):e?.status===401||e?.status===403||t.includes("UNAUTHENTICATED")||t.includes("PERMISSION_DENIED")?new de(t,e):e?.status>=400&&e?.status<500?new I(t,e):new F(t||"Vertex AI Error","VERTEXAI_ERROR",e?.status??500,e)}};l();var Ml=require("@google/generative-ai");ce();k();var vn=class extends Q{genAI;constructor(e){super(),this.genAI=new Ml.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",c=`https://generativelanguage.googleapis.com/upload/v1beta/files?key=${this.genAI.apiKey}`,p="----WebKitFormBoundary"+Math.random().toString(36).substring(2),m=JSON.stringify({file:{displayName:s}}),u=Buffer.concat([Buffer.from(`--${p}\r
338
441
  Content-Type: application/json\r
339
442
  \r
340
443
  ${m}\r
341
444
  `),Buffer.from(`--${p}\r
342
445
  Content-Type: ${i}\r
343
446
  \r
344
- `),r,Buffer.from(`\r
447
+ `),n,Buffer.from(`\r
345
448
  --${p}--\r
346
- `)]),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}`,r=await fetch(o,{method:"DELETE"});if(!r.ok){let s=await r.text();throw new Error(`Gemini file deletion failed: ${r.status} ${s}`)}}catch(t){throw this.handleError(t)}}getDisplayName(){return"Google Gemini"}async getModels(){return[{id:"gemini-3.1-flash-lite-preview",displayName:"Gemini 3.1 Flash-Lite Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0?(o.tools=[{functionDeclarations:e.tools.map(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}`),se(t,"Gemini",e.messages);let r=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await r.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessage(i)).response,m=[],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)}`),se(o,"Gemini",e.messages);let r=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),l=await r.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessageStream(i);for await(let p of 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 r=>(await t.embedContent(r)).embedding.values))}:{embeddings:[(await t.embedContent(e.input)).embedding.values]}}catch(t){throw this.handleError(t)}}extractSystemInstruction(e){let t=e.filter(o=>o.role==="system");if(t.length!==0)return t.map(o=>typeof o.content=="string"?o.content:o.content===null?"":o.content.map(r=>r.text).join(`
449
+ `)]),f=await fetch(c,{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}`),ee(t,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessage(i)).response,m=[],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)}`),ee(o,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),c=await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessageStream(i);for await(let p of c.stream){for(let m of p.candidates?.[0]?.content?.parts||[])m.functionCall?(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(`
347
450
  `)).join(`
348
- `)}async formatHistory(e,t={}){let o=e.filter(m=>m.role!=="system");if(o.length===0)return{history:[],lastUserMessage:""};let r=o[o.length-1],s=o.slice(0,o.length-1),{normalizeImagePart:i}=await Promise.resolve().then(()=>(pt(),No)),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 d=[];if(typeof m.content=="string"&&m.content)d.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(`
349
- `);f&&d.push({text:f})}for(let f of m.tool_calls)d.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:d}}return{role:m.role==="user"?"user":"model",parts:await a(m.content)}})),p=typeof r.content=="string"?r.content:await a(r.content);return{history: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 ve(e.message,e):new W(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};c();var Me=x(require("fs"),1),ws=x(require("path"),1);ne();var Xa="toolpack.config.json",Dr=new Map;async function Ya(n){for(;Dr.has(n);)await Dr.get(n);let e,t=new Promise(o=>{e=o});return Dr.set(n,t),()=>{Dr.delete(n),e()}}function Je(n){if(n&&Me.existsSync(n))return n;let e=ws.join(process.cwd(),Xa);return Me.existsSync(e)?e:null}function Lo(n){if(!n)return null;try{let e=Me.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}var Io=null;function Mr(n){if(Io)return Io;let e=n||Je();return Io=Lo(e)||{},Io}function Nr(){Io=null}function Za(n){return(Mr(n).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function jo(n){return Mr(n).ollama?.baseUrl||"http://localhost:11434"}async function el(n){let{type:e,value:t,configPath:o}=n,r=o||Je();r||(r=ws.join(process.cwd(),Xa));let s=await Ya(r);try{let i=Lo(r)||{};switch(i.hitl||(i.hitl={}),i.hitl.bypass||(i.hitl.bypass={}),e){case"tool":i.hitl.bypass.tools||(i.hitl.bypass.tools=[]),i.hitl.bypass.tools.includes(t)||i.hitl.bypass.tools.push(t);break;case"category":i.hitl.bypass.categories||(i.hitl.bypass.categories=[]),i.hitl.bypass.categories.includes(t)||i.hitl.bypass.categories.push(t);break;case"level":{i.hitl.bypass.levels||(i.hitl.bypass.levels=[]);let a=t;i.hitl.bypass.levels.includes(a)||i.hitl.bypass.levels.push(a);break}}try{Me.writeFileSync(r,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")}Nr()}finally{s()}}async function tl(n){let{type:e,value:t,configPath:o}=n,r=o||Je();if(!r)return;let s=await Ya(r);try{let i=Lo(r);if(!i?.hitl?.bypass)return;switch(e){case"tool":i.hitl.bypass.tools&&(i.hitl.bypass.tools=i.hitl.bypass.tools.filter(a=>a!==t));break;case"category":i.hitl.bypass.categories&&(i.hitl.bypass.categories=i.hitl.bypass.categories.filter(a=>a!==t));break;case"level":i.hitl.bypass.levels&&(i.hitl.bypass.levels=i.hitl.bypass.levels.filter(a=>a!==t));break}try{Me.writeFileSync(r,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")}Nr()}finally{s()}}c();c();ne();P();c();var Ts=x(require("http"),1);function ue(n,e,t,o,r=12e4){return new Promise((s,i)=>{let a=new URL(e,n),l={hostname:a.hostname,port:a.port,path:a.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:r},p=Ts.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 Ar(n,e,t,o=12e4,r){let s,i=!1;return r&&r.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let l=new URL(e,n),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=Ts.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(`
350
- `);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 Ne=class extends Z{config;baseUrl;timeout;modelName;constructor(e){super(),this.config=e,this.baseUrl=e.baseUrl||"http://localhost:11434",this.timeout=e.timeout||12e4,this.modelName=e.model}getDisplayName(){return"Ollama"}async getModels(){try{return(await this.listModels()).map(t=>({id:t.name,displayName:t.name,capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!0,vision:!0}}))}catch{return[]}}async connect(){let e=await this.listModels(),t=this.config.model.split(":")[0].toLowerCase();if(!e.some(r=>r.name.split(":")[0].toLowerCase()===t||r.name.toLowerCase()===this.config.model.toLowerCase()))throw new I(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
351
- Available models: ${e.map(r=>r.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await ue(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new W(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof W?e:new _e(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await ue(this.baseUrl,"/api/tags","GET",void 0,3e3),!0}catch{return!1}}async isModelAvailable(e){try{let t=await this.listModels(),o=(e||this.config.model).toLowerCase(),r=o.split(":")[0];return t.some(s=>s.name.split(":")[0].toLowerCase()===r||s.name.toLowerCase()===o)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await Promise.all(e.messages.map(i=>this.toOllamaMessage(i,e.mediaOptions))),r=e.model||this.config.model,s={model:r,messages:o,stream:!1,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${O(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] generate() request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),se(t,"Ollama",e.messages);try{let i=await ue(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 W?i:new _e(`Failed to generate with Ollama model "${r}": ${i.message}`,i)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),r=e.model||this.config.model,s={model:r,messages:o,stream:!0,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),h(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&h(`[Ollama][${t}] First tool: ${O(e.tools[0],800)}`),h(`[Ollama][${t}] NO TOOLS in request`)),h(`[Ollama][${t}] Stream request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),se(t,"Ollama",e.messages);let{stream:i}=Ar(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){De(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new _e(`Stream failed for Ollama model "${r}": ${a.message}`,a)}}async embed(e){let t=e.__toolpack_request_id||`emb-${Date.now()}`,o=typeof e.input=="string"?[e.input]:e.input,r=e.model||this.config.model;h(`[Ollama][${t}] Embedding request: model=${r}, inputs=${o.length}`);try{let s=await ue(this.baseUrl,"/api/embed","POST",{model:r,input:o},this.timeout);if(s.status!==200)throw this.handleHttpError(s.status,s.body);return{embeddings:JSON.parse(s.body).embeddings||[]}}catch(s){throw s instanceof W?s:new _e(`Embedding failed for Ollama model "${r}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",r=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(pt(),No));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+`
352
- `;else if(a.type==="image_url"||a.type==="image_data"||a.type==="image_file")try{let{data:l}=await s(a);r.push(l)}catch{a.type==="image_url"?o+=`[Image: ${a.image_url.url}]
451
+ `)}async formatHistory(e,t={}){let o=e.filter(m=>m.role!=="system");if(o.length===0)return{history:[],lastUserMessage:""};let n=o[o.length-1],s=o.slice(0,o.length-1),{normalizeImagePart:i}=await Promise.resolve().then(()=>(kt(),wn)),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),c=await Promise.all(s.map(async m=>{if(m.role==="tool"&&m.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(m.name||m.tool_call_id),response:{name:this.sanitizeToolName(m.name||m.tool_call_id),content:typeof m.content=="string"?m.content:JSON.stringify(m.content)}}}]};if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let u=[];if(typeof m.content=="string"&&m.content)u.push({text:m.content});else if(Array.isArray(m.content)){let 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:c,lastUserMessage:p}}handleError(e){return e.status===429?new Te(e.message,void 0,e):e.status>=400&&e.status<500?new I(e.message,e):e.message&&e.message.includes("API key")?new de(e.message,e):new F(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();var Fe=x(require("fs"),1),Gs=x(require("path"),1);ce();var Ol="toolpack.config.json",wr=new Map;async function Nl(r){for(;wr.has(r);)await wr.get(r);let e,t=new Promise(o=>{e=o});return wr.set(r,t),()=>{wr.delete(r),e()}}function rt(r){if(r&&Fe.existsSync(r))return r;let e=Gs.join(process.cwd(),Ol);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 Cn=null;function Tr(r){if(Cn)return Cn;let e=r||rt();return Cn=kn(e)||{},Cn}function xr(){Cn=null}function Al(r){return(Tr(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function Pn(r){return Tr(r).ollama?.baseUrl||"http://localhost:11434"}async function Il(r){let{type:e,value:t,configPath:o}=r,n=o||rt();n||(n=Gs.join(process.cwd(),Ol));let s=await Nl(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")}xr()}finally{s()}}async function Ll(r){let{type:e,value:t,configPath:o}=r,n=o||rt();if(!n)return;let s=await Nl(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")}xr()}finally{s()}}l();l();ce();k();l();var Bs=x(require("http"),1);function ve(r,e,t,o,n=12e4){return new Promise((s,i)=>{let a=new URL(e,r),c={hostname:a.hostname,port:a.port,path:a.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:n},p=Bs.default.request(c,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 vr(r,e,t,o=12e4,n){let s,i=!1;return n&&n.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let c=new URL(e,r),p={hostname:c.hostname,port:c.port,path:c.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},m=await new Promise((f,b)=>{s=Bs.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 Q{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 ve(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new F(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof F?e:new Ie(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await ve(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}`),ee(t,"Ollama",e.messages);try{let i=await ve(this.baseUrl,"/api/chat","POST",s,this.timeout);if(i.status!==200)throw this.handleHttpError(i.status,i.body);let a=JSON.parse(i.body),c=[];if(a.message?.tool_calls)for(let m of a.message.tool_calls)c.push({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}});let p={content:a.message?.content||null,usage:a.prompt_eval_count!=null?{prompt_tokens:a.prompt_eval_count||0,completion_tokens:a.eval_count||0,total_tokens:(a.prompt_eval_count||0)+(a.eval_count||0)}:void 0,finish_reason:c.length>0?"tool_calls":a.done?"stop":void 0,tool_calls:c.length>0?c:void 0,raw:a};return h(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${O(p.content,200)}`),p}catch(i){throw i instanceof F?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}`),ee(t,"Ollama",e.messages);let{stream:i}=vr(this.baseUrl,"/api/chat",s,this.timeout,e.signal);try{for await(let a of i)try{let c=JSON.parse(a);if(c.message?.content){let p=c.message.tool_calls&&c.message.tool_calls.length>0;yield{delta:c.message.content,finish_reason:c.done&&!p?"stop":void 0,usage:c.done&&c.prompt_eval_count!=null?{prompt_tokens:c.prompt_eval_count||0,completion_tokens:c.eval_count||0,total_tokens:(c.prompt_eval_count||0)+(c.eval_count||0)}:void 0}}if(c.message?.tool_calls&&c.message.tool_calls.length>0){let p=c.message.tool_calls.map(m=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}}));h(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(c.done&&!c.message?.content&&!c.message?.tool_calls){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 ve(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 F?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(),wn));if(typeof e.content=="string")o=e.content;else if(e.content!==null){for(let a of e.content)if(a.type==="text")o+=a.text+`
455
+ `;else if(a.type==="image_url"||a.type==="image_data"||a.type==="image_file")try{let{data:c}=await s(a);n.push(c)}catch{a.type==="image_url"?o+=`[Image: ${a.image_url.url}]
353
456
  `:o+=`[Unresolvable Image]
354
- `}o=o.trim()}let i={role:e.role,content:o};return r.length>0&&(i.images=r),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?i.tool_calls=e.tool_calls.map(a=>({function:{name:this.sanitizeToolName(a.function.name),arguments:typeof a.function.arguments=="string"?JSON.parse(a.function.arguments||"{}"):a.function.arguments}})):e.role==="tool"&&(i.content=o||JSON.stringify(e.content),e.name&&(i.tool_name=this.sanitizeToolName(e.name))),i}handleHttpError(e,t){let o=`Ollama error (HTTP ${e})`;try{let r=JSON.parse(t);r.error&&(o=`Ollama: ${r.error}`)}catch{}return e===404?new I(`Model not found: ${o}`):new W(o,"OLLAMA_ERROR",e)}};c();var mt=class extends Z{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await ue(this.baseUrl,"/api/tags","GET",void 0,5e3);if(t.status!==200)return[];e=JSON.parse(t.body).models||[]}catch{return[]}return Promise.all(e.map(t=>this.buildModelInfo(t)))}async generate(e){return this.getAdapterForModel(e.model).generate(this.stripToolsIfNeeded(e))}async*stream(e){yield*this.getAdapterForModel(e.model).stream(this.stripToolsIfNeeded(e))}async embed(e){return this.getAdapterForModel(e.model).embed(e)}async disconnect(){this.adapterCache.clear(),this.capabilityCache.clear()}stripToolsIfNeeded(e){let t=this.capabilityCache.get(e.model);if(t&&!t.toolCalling&&e.tools&&e.tools.length>0){let{tools:o,tool_choice:r,...s}=e,i=s,a={role:"system",content:"You do not have access to any tools or functions. Do not attempt to call tools, output tool invocations, or reference tool usage. Answer the user directly using only your own knowledge."};return i.messages=[...i.messages,a],i}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new Ne({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,o=!1,r=!1;try{let a=await ue(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(a.status===200){let p=(JSON.parse(a.body).details?.families||[]).map(m=>m.toLowerCase());o=p.some(m=>["clip","mllama"].includes(m)),r=p.some(m=>m.includes("bert")||m.includes("nomic"))}}catch{}t=await this.probeToolSupport(e.name);let s=e.name.toLowerCase();o||(o=["llava","vision","bakllava","moondream"].some(l=>s.includes(l))),r||(r=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(l=>s.includes(l)));let i={toolCalling:t,vision:o,embeddings:r};return this.capabilityCache.set(e.name,i),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:r,vision:o}}}async probeToolSupport(e){try{let t=await ue(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 xs=[{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 ol(){return xs[0].model}function rl(n){let e=n.toLowerCase();return xs.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function nl(){return[...xs]}c();var vs=x(require("openai"),1);ne();P();var Qe=class extends Z{client;constructor(e,t){super(),this.client=new vs.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()}`,r={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"}:void 0,stream:!1},s=new Map;e.tools&&e.tools.length>0&&(r.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}}}),r.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),h(`[OpenAI][${t}] First tool: ${O(r.tools[0],800)}`)),h(`[OpenAI][${t}] Request params: ${O({model:r.model,messages_count:r.messages.length,has_tools:!!r.tools,tools_count:r.tools?.length,tool_choice:r.tool_choice},800)}`),se(t,"OpenAI",r.messages);let i=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0);De(`[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()}`,r={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?(r.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}}}),r.tool_choice=e.tool_choice||"auto",h(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),h(`[OpenAI][${t}] First tool: ${O(r.tools[0],800)}`)):h(`[OpenAI][${t}] NO TOOLS in request`),h(`[OpenAI][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice??"unset"}`),se(t,"OpenAI",r.messages);let i=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0),a=new Map;for await(let l of i){let p=l.choices[0];if(p.finish_reason&&De(`[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),De(`[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(r=>r.embedding),usage:o.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(s=>({id:s.id,type:"function",function:{name:this.sanitizeToolName(s.function.name),arguments:s.function.arguments}}))};if(typeof e.content=="string")return{role:e.role,content:e.content};if(e.content===null||e.content===void 0)return{role:e.role,content:""};let{normalizeImagePart:o}=await Promise.resolve().then(()=>(pt(),No)),r=await Promise.all(e.content.map(async s=>{if(s.type==="text")return{type:"text",text:s.text};if(s.type==="image_url")return{type:"image_url",image_url:{url:s.image_url.url}};if(s.type==="image_data"||s.type==="image_file"){let{data:i,mimeType:a}=await o(s);return{type:"image_url",image_url:{url:`data:${a};base64,${i}`}}}return null}));return{role:e.role,content:r.filter(Boolean)}}handleError(e){if(e instanceof vs.default.APIError){let t=e.message;return e.status===401?new ve(t,e):e.status===429?new Ce(t,void 0,e):e.status&&e.status>=400&&e.status<500?new I(t,e):new W(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new W("Unknown error","UNKNOWN",500,e)}};c();var sl="https://openrouter.ai/api/v1",Fo=class extends Qe{name="openrouter";_apiKey;constructor(e,t={}){super(e,sl),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(`${sl}/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"}};pt();c();$o();c();$o();var yo=class{tools=new Map;projects=new Map;config=V;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),o=new Set,r=[];for(let s of[...e,...t])o.has(s.name)||(o.add(s.name),r.push(s));return r}getSchemas(e){return(e?e.map(o=>this.tools.get(o)).filter(Boolean):this.getEnabled()).map(o=>({name:o.name,displayName:o.displayName,description:o.description,parameters:o.parameters,category:o.category}))}getByNames(e){return e.map(t=>this.tools.get(t)).filter(Boolean)}getByCategories(e){let t=new Set(e);return Array.from(this.tools.values()).filter(o=>t.has(o.category))}getCategories(){let e=new Set;for(let t of this.tools.values())e.add(t.category);return Array.from(e)}getAll(){return Array.from(this.tools.values())}setConfig(e){this.config=e}getConfig(){return this.config}get size(){return this.tools.size}async validateDependencies(e){let t=e.dependencies;if(!t||Object.keys(t).length===0)return[];let o=[];for(let r of Object.keys(t))try{await import(r)}catch{o.push(r)}return o}async loadProject(e){let t=await this.validateDependencies(e);if(t.length>0)throw new Error(`Tool project "${e.manifest.name}" has missing dependencies: ${t.join(", ")}. Install them with: npm install ${t.join(" ")}`);this.projects.set(e.manifest.name,e);for(let o of e.tools)this.register(o)}async loadProjects(e){for(let t of e)await this.loadProject(t)}getProject(e){return this.projects.get(e)}getProjects(){return Array.from(this.projects.values())}getProjectNames(){return Array.from(this.projects.keys())}async loadBuiltIn(){let{fsToolsProject:e}=await Promise.resolve().then(()=>(Gs(),wp)),{execToolsProject:t}=await Promise.resolve().then(()=>(Xs(),lm)),{systemToolsProject:o}=await Promise.resolve().then(()=>(ii(),Wm)),{httpToolsProject:r}=await Promise.resolve().then(()=>(ui(),Cd)),{githubToolsProject:s}=await Promise.resolve().then(()=>(Pi(),$u)),{webToolsProject:i}=await Promise.resolve().then(()=>(ji(),Xf)),{codingToolsProject:a}=await Promise.resolve().then(()=>(oa(),Fh)),{gitToolsProject:l}=await Promise.resolve().then(()=>(na(),fy)),{diffToolsProject:p}=await Promise.resolve().then(()=>(aa(),$y)),{dbToolsProject:m}=await Promise.resolve().then(()=>(ma(),tb)),{cloudToolsProject:d}=await Promise.resolve().then(()=>(ua(),db));await this.loadProjects([e,t,o,r,s,i,a,l,p,m,d])}};Ri();c();P();function ub(n){if(!n.key||!/^[a-z0-9-]+$/.test(n.key))throw new Error(`Invalid tool project key: "${n.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!n.name.trim())throw new Error("Tool project name cannot be empty.");if(!n.tools||n.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of n.tools){if(!t.name)throw new Error("Tool is missing a name.");if(!t.description)throw new Error(`Tool "${t.name}" is missing a description.`);if(!t.parameters)throw new Error(`Tool "${t.name}" is missing parameters.`);if(typeof t.execute!="function")throw new Error(`Tool "${t.name}" is missing an execute function.`);t.category!==n.category&&M(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${n.category}".`)}let e=n.tools.map(t=>t.name);return{manifest:{key:n.key,name:n.name,displayName:n.displayName,version:n.version,description:n.description,author:n.author,repository:n.repository,category:n.category,tools:e},dependencies:n.dependencies,tools:n.tools}}Gs();Xs();ii();ui();Pi();ji();oa();na();aa();ma();ua();c();c();var fb=require("child_process");P();function A(n,e){if(n.includes("\0")||n.includes(`
355
- `)||n.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return n}function BT(n){let e=typeof n.stdout=="string"?n.stdout:"",t=typeof n.stderr=="string"?n.stderr:"",o=n.status??"unknown",r=t.split(/\r?\n/).filter(i=>i.trim().length>0),s=r.find(i=>i.toLowerCase().startsWith("error:"))||r[0]||n.message||"";return`kubectl failed (exit code ${o})${s?`: ${s.trim()}`:""}
457
+ `}o=o.trim()}let i={role:e.role,content:o};return n.length>0&&(i.images=n),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?i.tool_calls=e.tool_calls.map(a=>({function:{name:this.sanitizeToolName(a.function.name),arguments:typeof a.function.arguments=="string"?JSON.parse(a.function.arguments||"{}"):a.function.arguments}})):e.role==="tool"&&(i.content=o||JSON.stringify(e.content),e.name&&(i.tool_name=this.sanitizeToolName(e.name))),i}handleHttpError(e,t){let o=`Ollama error (HTTP ${e})`;try{let n=JSON.parse(t);n.error&&(o=`Ollama: ${n.error}`)}catch{}return e===404?new I(`Model not found: ${o}`):new F(o,"OLLAMA_ERROR",e)}};l();var Pt=class extends Q{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 ve(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 ve(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(a.status===200){let p=(JSON.parse(a.body).details?.families||[]).map(m=>m.toLowerCase());o=p.some(m=>["clip","mllama"].includes(m)),n=p.some(m=>m.includes("bert")||m.includes("nomic"))}}catch{}t=await this.probeToolSupport(e.name);let s=e.name.toLowerCase();o||(o=["llava","vision","bakllava","moondream"].some(c=>s.includes(c))),n||(n=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(c=>s.includes(c)));let i={toolCalling:t,vision:o,embeddings:n};return this.capabilityCache.set(e.name,i),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:n,vision:o}}}async probeToolSupport(e){try{let t=await ve(this.baseUrl,"/api/chat","POST",{model:e,messages:[{role:"user",content:"hi"}],tools:[{type:"function",function:{name:"__probe",description:"probe",parameters:{type:"object",properties:{}}}}],stream:!1},1e4);return t.status>=400?!1:!JSON.parse(t.body).error}catch{return!1}}};l();var zs=[{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 jl(){return zs[0].model}function Fl(r){let e=r.toLowerCase();return zs.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function ql(){return[...zs]}l();var Hs=x(require("openai"),1);ce();k();var st=class extends Q{client;constructor(e,t){super(),this.client=new Hs.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)}`),ee(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 c=i.choices[0],p,m=c.message.tool_calls;return m&&m.length>0&&(p=m.map(u=>({id:u.id,name:s.get(u.function.name)||u.function.name,arguments:JSON.parse(u.function.arguments)}))),{content:c.message.content,usage:i.usage?{prompt_tokens:i.usage.prompt_tokens,completion_tokens:i.usage.completion_tokens,total_tokens:i.usage.total_tokens}:void 0,finish_reason:c.finish_reason,tool_calls:p,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,n={messages:await Promise.all(e.messages.map(c=>this.toOpenAIMessage(c,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!0},s=new Map;e.tools&&e.tools.length>0?(n.tools=e.tools.map(c=>{let p=this.sanitizeToolName(c.function.name);return s.set(p,c.function.name),{type:"function",function:{name:p,description:c.function.description,parameters:c.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",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"}`),ee(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0),a=new Map;for await(let c of i){let p=c.choices[0];if(p.finish_reason&&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:c.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:c.usage}),p.finish_reason==="tool_calls"&&a.size>0){let m=Array.from(a.values()).map(u=>({id:u.id,name:s.get(u.name)||u.name,arguments:JSON.parse(u.args||"{}")}));h(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(u=>u.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,o=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:o.data.map(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(),wn)),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 Hs.default.APIError){let t=e.message;return e.status===401?new de(t,e):e.status===429?new Te(t,void 0,e):e.status&&e.status>=400&&e.status<500?new I(t,e):new F(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new F("Unknown error","UNKNOWN",500,e)}};l();var Wl="https://openrouter.ai/api/v1",Sn=class extends st{name="openrouter";_apiKey;constructor(e,t={}){super(e,Wl),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(`${Wl}/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();l();fn();l();fn();var on=class{tools=new Map;projects=new Map;config=Z;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),o=new Set,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(()=>(ui(),tm)),{execToolsProject:t}=await Promise.resolve().then(()=>(xi(),Bm)),{systemToolsProject:o}=await Promise.resolve().then(()=>(Ei(),Cd)),{httpToolsProject:n}=await Promise.resolve().then(()=>(Li(),su)),{githubToolsProject:s}=await Promise.resolve().then(()=>(Ji(),mf)),{webToolsProject:i}=await Promise.resolve().then(()=>(la(),Og)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Ra(),Py)),{gitToolsProject:c}=await Promise.resolve().then(()=>($a(),rb)),{diffToolsProject:p}=await Promise.resolve().then(()=>(Ma(),bb)),{dbToolsProject:m}=await Promise.resolve().then(()=>(Ia(),zb)),{cloudToolsProject:u}=await Promise.resolve().then(()=>(ja(),ow)),{slackToolsProject:f}=await Promise.resolve().then(()=>(Ha(),Fw));await this.loadProjects([e,t,o,n,s,i,a,c,p,m,u,f])}};Xi();l();k();function qw(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}}ui();xi();Ei();Li();Ji();la();Ra();$a();Ma();Ia();ja();l();l();var Ww=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 Nv(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()}`:""}
356
459
  STDOUT:
357
460
  ${e}
358
461
  STDERR:
359
- ${t}`}function re(n,e,t=3e4){n.forEach((o,r)=>A(o,`kubectl argument #${r}`)),h(`[k8s-tools] execute: kubectl ${n.join(" ")}`);try{return(0,fb.execFileSync)("kubectl",n,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return BT(o)}}function zT(n){if(!n)return 3e5;let e=n.trim().toLowerCase(),t=/^([0-9]+)(s|m|h)?$/.exec(e);if(!t)return 3e5;let o=Number(t[1]);switch(t[2]){case"h":return o*60*60*1e3;case"m":return o*60*1e3;default:return o*1e3}}var fe="kubernetes";function gb(n){if(!n)return;if(typeof n=="string")return n;let e=Object.entries(n).filter(([,t])=>t!==void 0&&t!=="");if(e.length)return e.map(([t,o])=>`${A(t,"label key")}=${A(o,"label value")}`).join(",")}var En={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:fe,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter pods."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter pods.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the pod list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"If true, list pods across all namespaces.",default:!1}},required:[]},execute:async n=>{let e=["get","pods"],t=n.output;t?e.push("-o",t):e.push("-o","wide"),n.allNamespaces&&e.push("--all-namespaces"),n.namespace&&!n.allNamespaces&&e.push("-n",A(n.namespace,"namespace"));let o=gb(n.labelSelector)??n.labels;return o&&e.push("-l",A(o,"labels")),re(e)}},Dn={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:fe,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to describe, such as pod, service, deployment."},name:{type:"string",description:"Resource name. Optional for cluster-wide descriptions."},namespace:{type:"string",description:"Namespace containing the resource."}},required:["resource"]},execute:async n=>{let t=["describe",A(n.resource,"resource")];return n.name&&t.push(A(n.name,"name")),n.namespace&&t.push("-n",A(n.namespace,"namespace")),re(t)}},Mn={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:fe,parameters:{type:"object",properties:{podName:{type:"string",description:"The name of the pod to fetch logs from."},namespace:{type:"string",description:"Namespace of the pod."},container:{type:"string",description:"Container name inside the pod."},tailLines:{type:"number",description:"Number of log lines to show from the end.",default:100},since:{type:"string",description:"Return logs newer than a relative duration like 5m or 1h."}},required:["podName"]},execute:async n=>{let e=["logs",A(n.podName,"podName")];return n.container&&e.push("-c",A(n.container,"container")),n.namespace&&e.push("-n",A(n.namespace,"namespace")),typeof n.tailLines=="number"&&e.push("--tail",`${n.tailLines}`),n.since&&e.push("--since",A(n.since,"since")),re(e)}},Nn={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:fe,parameters:{type:"object",properties:{path:{type:"string",description:"Path to the manifest file to apply."},manifest:{type:"string",description:"Inline YAML manifest to apply if no path is provided."},namespace:{type:"string",description:"Namespace to apply the manifest into, if supported by the manifest."},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without applying changes.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will change cluster state by applying a Kubernetes manifest.",showArgs:["path","namespace"]},execute:async n=>{let e=n.path,t=n.manifest,o=["apply"];if(n.dryRun&&o.push("--dry-run=client"),o.push("-f"),e)return o.push(A(e,"path")),n.namespace&&o.push("-n",A(n.namespace,"namespace")),re(o);if(!t)throw new Error("Either path or manifest is required to apply a Kubernetes manifest.");return n.namespace&&o.push("-n",A(n.namespace,"namespace")),o.push("-"),re(o,t)}},An={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:fe,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to delete, such as pod, service, deployment."},name:{type:"string",description:"Name of the resource to delete."},namespace:{type:"string",description:"Namespace containing the resource."},path:{type:"string",description:"Path to a manifest file that contains the resources to delete."},force:{type:"boolean",description:"Force deletion of the resource.",default:!1},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without deleting resources.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will delete resources from the Kubernetes cluster.",showArgs:["resource","name","path"]},execute:async n=>{let e=n.path,t=n.resource,o=n.name;if(e){let s=["delete"];return n.dryRun&&s.push("--dry-run=client"),s.push("-f",A(e,"path")),n.namespace&&s.push("-n",A(n.namespace,"namespace")),re(s)}if(!t||!o)throw new Error("resource and name are required unless a manifest path is provided.");let r=["delete",A(t,"resource"),A(o,"name")];return n.namespace&&r.push("-n",A(n.namespace,"namespace")),n.force&&r.push("--force","--grace-period=0"),n.dryRun&&r.push("--dry-run=client"),re(r)}},On={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:fe,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},output:{type:"string",description:"Output format for the service list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List services across all namespaces.",default:!1}},required:[]},execute:async n=>{let e=["get","services"],t=n.output;return e.push("-o",t||"wide"),n.allNamespaces&&e.push("--all-namespaces"),n.namespace&&!n.allNamespaces&&e.push("-n",A(n.namespace,"namespace")),re(e)}},In={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:fe,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter deployments."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter deployments.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the deployment list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List deployments across all namespaces.",default:!1}},required:[]},execute:async n=>{let e=["get","deployments"],t=n.output;e.push("-o",t||"wide"),n.allNamespaces&&e.push("--all-namespaces"),n.namespace&&!n.allNamespaces&&e.push("-n",A(n.namespace,"namespace"));let o=gb(n.labelSelector)??n.labels;return o&&e.push("-l",A(o,"labels")),re(e)}},Ln={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:fe,parameters:{type:"object",properties:{name:{type:"string",description:"ConfigMap name."},namespace:{type:"string",description:"Namespace containing the ConfigMap."},output:{type:"string",description:"Output format, such as yaml or json.",enum:["yaml","json"],default:"yaml"}},required:["name"]},execute:async n=>{let e=["get","configmap",A(n.name,"name"),"-o",n.output||"yaml"];return n.namespace&&e.push("-n",A(n.namespace,"namespace")),re(e)}},jn={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:fe,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async n=>re(["config","use-context",A(n.context,"context")])},Fn={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:fe,parameters:{type:"object",properties:{output:{type:"string",description:"Output format for the namespace list.",enum:["wide","name","json","yaml"],default:"wide"}},required:[]},execute:async n=>re(["get","namespaces","-o",n.output||"wide"])},qn={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:fe,parameters:{type:"object",properties:{name:{type:"string",description:"Deployment name to wait for."},namespace:{type:"string",description:"Namespace containing the deployment."},timeout:{type:"string",description:"Timeout duration, e.g. 300s or 5m.",default:"300s"}},required:["name"]},execute:async n=>{let e=n.timeout,t=["rollout","status",`deployment/${A(n.name,"name")}`,"--timeout",e||"300s"];return n.namespace&&t.push("-n",A(n.namespace,"namespace")),re(t,void 0,zT(e))}};var hb={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:[En,Dn,Mn,Nn,An,On,In,Ln,jn,Fn,qn]};c();c();var yb=require("child_process"),bb=require("events");P();var gr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},Te=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},bo=class extends bb.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 Te("Client is shutting down");if(this.buffer="",this.process=(0,yb.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 Te("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=>{M(`[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 Te(`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(`
360
- `))!==-1;){let r=this.buffer.slice(0,o).trim();if(this.buffer=this.buffer.slice(o+1),r)try{let s=JSON.parse(r);this.handleMessage(s)}catch{}}}handleMessage(t){if(t.id&&(t.result!==void 0||t.error)){let o=this.messageQueue.get(t.id);o&&(o.timer&&clearTimeout(o.timer),t.error?o.reject(new Error(t.error.message)):o.resolve(t.result),this.messageQueue.delete(t.id))}else t.method&&(this.emit("notification",t),this.emit(t.method,t.params))}async callTool(t,o={},r){return this.request("tools/call",{name:t,arguments:o},r)}async readResource(t,o){return this.request("resources/read",{uri:t},o)}async request(t,o,r){if(!this.process||!this.process.stdin)throw new Te("Client not connected");let s=this.nextId++,i=r??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 gr(t,i)))},i)),this.messageQueue.set(s,{resolve:l,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
361
- `)}catch(d){m&&clearTimeout(m),this.messageQueue.delete(s),p(d)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new Te("Client disconnecting")),!this.process){this._shuttingDown=!1;return}let o=this.process;return new Promise(r=>{let s=!1,i=()=>{s||(s=!0,this.process=null,this._connected=!1,this._shuttingDown=!1,r())};o.once("exit",i),o.kill("SIGTERM"),setTimeout(()=>{if(!s){try{o.kill("SIGKILL")}catch{}i()}},t)})}kill(){this._shuttingDown=!0,this.rejectAllPending(new Te("Client killed")),this.process&&(this.process.kill("SIGKILL"),this.process=null),this._connected=!1,this._shuttingDown=!1}rejectAllPending(t){for(let[o,r]of this.messageQueue)r.timer&&clearTimeout(r.timer),r.reject(t);this.messageQueue.clear()}};P();var hr=class{constructor(e){this.config=e}config;clients=new Map;serverConfigs=new Map;toolDefinitions=new Map;toolOwners=new Map;async connectServer(e){let{name:t,displayName:o,toolPrefix:r,...s}=e;C(`[MCP] Connecting to server: ${o||t}`);try{let i=new bo({...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 oe(`[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){M(`[MCP] Server ${e} not found`);return}C(`[MCP] Disconnecting from ${e}`);for(let[o,r]of this.toolOwners)r===e&&(this.toolDefinitions.delete(o),this.toolOwners.delete(o));await t.disconnect(),this.clients.delete(e),this.serverConfigs.delete(e)}async disconnectAll(){let e=Array.from(this.clients.keys()).map(t=>this.disconnectServer(t));await Promise.allSettled(e)}getToolDefinitions(){return Array.from(this.toolDefinitions.values())}getConnectedServers(){return Array.from(this.clients.keys())}isServerConnected(e){return this.clients.get(e)?.connected??!1}convertMcpTool(e,t,o,r){let s={type:"object",properties:e.inputSchema.properties||{},required:e.inputSchema.required||[]};return{name:`${o}${e.name}`,displayName:e.name,description:e.description||`MCP tool from ${t}`,category:"mcp",parameters:s,execute:async i=>{try{C(`[MCP] Executing ${e.name} on ${t}`);let a=await r.callTool(e.name,i);return JSON.stringify(a)}catch(a){throw oe(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{oe(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{M(`[MCP] ${t} closed with code ${o}`)}),e.on("reconnecting",({attempt:o,max:r})=>{C(`[MCP] ${t} reconnecting (${o}/${r})`)}),e.on("reconnected",({attempt:o})=>{C(`[MCP] ${t} reconnected after ${o} attempts`),this.refreshServerTools(t).catch(r=>{oe(`[MCP] ${t} tool refresh failed after reconnect: ${r}`)})}),e.on("reconnect_failed",o=>{oe(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{C(`[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||[];C(`[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 Wn(n){let e=new hr(n);await e.connectAll();let t=e.getToolDefinitions();return{manifest:{key:"mcp-tools",name:"mcp-tools",displayName:"MCP Tools",version:"1.0.0",description:`Tools from ${e.getConnectedServers().length} MCP server(s)`,category:"mcp",author:"Toolpack SDK",tools:t.map(r=>r.name)},tools:t,mcpManager:e}}async function Un(n){"mcpManager"in n&&await n.mcpManager.disconnectAll()}c();c();c();c();var Gn=`
462
+ ${t}`}function me(r,e,t=3e4){r.forEach((o,n)=>A(o,`kubectl argument #${n}`)),h(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return(0,Ww.execFileSync)("kubectl",r,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return Nv(o)}}function Av(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 Se="kubernetes";function Uw(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 es={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:Se,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=Uw(r.labelSelector)??r.labels;return o&&e.push("-l",A(o,"labels")),me(e)}},ts={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:Se,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")),me(t)}},os={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:Se,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")),me(e)}},ns={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:Se,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")),me(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("-"),me(o,t)}},rs={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:Se,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")),me(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"),me(n)}},ss={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:Se,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")),me(e)}},is={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:Se,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=Uw(r.labelSelector)??r.labels;return o&&e.push("-l",A(o,"labels")),me(e)}},as={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:Se,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")),me(e)}},ls={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:Se,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>me(["config","use-context",A(r.context,"context")])},cs={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:Se,parameters:{type:"object",properties:{output:{type:"string",description:"Output format for the namespace list.",enum:["wide","name","json","yaml"],default:"wide"}},required:[]},execute:async r=>me(["get","namespaces","-o",r.output||"wide"])},ps={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:Se,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")),me(t,void 0,Av(e))}};var Gw={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:[es,ts,os,ns,rs,ss,is,as,ls,cs,ps]};Ha();l();l();var Bw=require("child_process"),zw=require("events");k();var nr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},$e=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},nn=class extends zw.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 $e("Client is shutting down");if(this.buffer="",this.process=(0,Bw.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 $e("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 $e(`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 $e("Client not connected");let s=this.nextId++,i=n??this.defaultTimeoutMs,a={jsonrpc:"2.0",id:s,method:t,params:o};return new Promise((c,p)=>{let m;i>0&&(m=setTimeout(()=>{let u=this.messageQueue.get(s);u&&(this.messageQueue.delete(s),u.reject(new nr(t,i)))},i)),this.messageQueue.set(s,{resolve:c,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 $e("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 $e("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 rr=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 nn({...s,requestTimeoutMs:s.requestTimeoutMs??this.config.defaultTimeoutMs,autoReconnect:s.autoReconnect??this.config.autoReconnect??!0});this.setupClientEvents(i,t),await i.connect(),this.clients.set(t,i),this.serverConfigs.set(t,e),await this.discoverServerTools(t,i,e)}catch(i){throw pe(`[MCP] Failed to connect to ${t}: ${i}`),i}}async connectAll(){let e=this.config.servers.filter(t=>t.autoConnect!==!1).map(t=>this.connectServer(t));await Promise.allSettled(e)}async disconnectServer(e){let t=this.clients.get(e);if(!t){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 pe(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{pe(`[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=>{pe(`[MCP] ${t} tool refresh failed after reconnect: ${n}`)})}),e.on("reconnect_failed",o=>{pe(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{P(`[MCP] ${t} notification: ${JSON.stringify(o)}`)})}removeServerToolDefinitions(e){for(let[t,o]of this.toolOwners)o===e&&(this.toolDefinitions.delete(t),this.toolOwners.delete(t))}async discoverServerTools(e,t,o){let s=(await t.request("tools/list"))?.tools||[];P(`[MCP] Discovered ${s.length} tools from ${e}`),this.removeServerToolDefinitions(e);let i=o.toolPrefix||`mcp.${e}.`;for(let a of s){let c=this.convertMcpTool(a,e,i,t);this.toolDefinitions.set(c.name,c),this.toolOwners.set(c.name,e)}}async refreshServerTools(e){let t=this.clients.get(e),o=this.serverConfigs.get(e);!t||!o||await this.discoverServerTools(e,t,o)}};async function ms(r){let e=new rr(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 ds(r){"mcpManager"in r&&await r.mcpManager.disconnectAll()}l();var H=x(require("fs/promises"),1),te=x(require("path"),1);function Ja(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 Va(r){let e=r.match(/\[(.*)\]/);return!e||!e[1]?[]:e[1].split(",").map(t=>t.trim().replace(/"/g,"")).filter(Boolean)}function Ka(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 ut(r,e){let t=r.match(new RegExp(`## ${e}\\n\\n([\\s\\S]*?)(?=\\n## |$)`));return t&&t[1]?t[1].trim():""}async function Hw(r,e){async function t(o){let n;try{n=await H.readdir(o)}catch{return null}for(let s of n){let i=te.join(o,s),a;try{a=await H.stat(i)}catch{continue}if(a.isDirectory()){let c=await t(i);if(c)return c}else if(a.isFile()&&s===`${e}.skill.md`)return i}return null}return t(r)}async function Iv(r){let e=[];async function t(o){let n;try{n=await H.readdir(o)}catch{return}for(let s of n){let i=te.join(o,s),a;try{a=await H.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function Lv(r){let{name:e,title:t,description:o,triggers:n,instructions:s,examples:i,tags:a}=r,c=new Date().toISOString(),p=a&&a.length>0?a.map(u=>`"${u}"`).join(", "):"",m=["---",`name: ${e}`,`title: ${t}`,"version: 1.0.0",`updated: ${c}`,`tags: [${p}]`,"---","","## Description","",o,"","## Triggers","",n.map(u=>`- "${u}"`).join(`
467
+ `),"","## Instructions","",s,""];return i&&m.push("## Examples","",i,""),m.join(`
468
+ `)}function jv(r){return{name:"skill.create",displayName:"Create Skill",description:"Create a new .skill.md file in the skill library.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:'Skill name in kebab-case (e.g. "code-review"). Used as the filename.'},title:{type:"string",description:"Human-readable title for the skill (max 100 chars)."},description:{type:"string",description:"Short description for BM25 search indexing (max 300 chars)."},triggers:{type:"array",items:{type:"string"},description:"List of trigger phrases that activate this skill (min 1, max 10)."},instructions:{type:"string",description:"Behavioral instructions injected into context when the skill activates (max 2000 chars)."},examples:{type:"string",description:"Optional examples section (max 3000 chars, never auto-injected)."},tags:{type:"array",items:{type:"string"},description:"Optional tags for filtering and search (max 10)."},subfolder:{type:"string",description:'Optional subfolder within the skills directory (e.g. "coding").'}},required:["name","title","description","triggers","instructions"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers??[],i=e.instructions,a=e.examples,c=e.tags??[],p=e.subfolder;if(!/^[a-z][a-z0-9-]*$/.test(t))return JSON.stringify({error:"invalid_name",message:"Skill name must be kebab-case (lowercase letters, numbers, hyphens, starting with a letter)"},null,2);let m=p?te.join(r,p):r;await H.mkdir(m,{recursive:!0});let u=te.join(m,`${t}.skill.md`);try{return await H.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=Lv({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:c});return await H.writeFile(u,f,"utf-8"),JSON.stringify({success:!0,skill:t,path:u,message:`Skill "${o}" created successfully`},null,2)}}}function Fv(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 Hw(r,t);if(!n)return JSON.stringify({error:"skill_not_found",message:`Skill "${t}" not found. Use skill.list to see available skills.`},null,2);let s=(await H.readFile(n,"utf-8")).replace(/\r\n/g,`
469
+ `),i=Ja(s),a={name:i.name||t,title:i.title||t,version:i.version,tags:i.tags?Va(i.tags):[],updated:i.updated,path:n};return JSON.stringify(o==="metadata"?{skill:t,metadata:a}:o==="description"?{skill:t,description:ut(s,"Description")}:o==="triggers"?{skill:t,triggers:Ka(s)}:o==="instructions"?{skill:t,instructions:ut(s,"Instructions")}:o==="examples"?{skill:t,examples:ut(s,"Examples")}:{skill:t,path:n,metadata:a,description:ut(s,"Description"),triggers:Ka(s),instructions:ut(s,"Instructions"),examples:ut(s,"Examples")||void 0},null,2)}}}function qv(r){return{name:"skill.update",displayName:"Update Skill",description:"Update fields of an existing skill. Only provided fields are changed.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:"Skill name to update."},title:{type:"string",description:"New title (optional)."},description:{type:"string",description:"New description replacing the existing one (optional)."},triggers:{type:"array",items:{type:"string"},description:"New triggers list replacing the existing one (optional)."},instructions:{type:"string",description:"New instructions replacing the existing ones (optional)."},addExamples:{type:"string",description:"Additional examples text to append to the Examples section (optional)."},addTags:{type:"array",items:{type:"string"},description:"Tags to add to the existing tags (optional)."}},required:["name"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers,i=e.instructions,a=e.addExamples,c=e.addTags,p=await Hw(r,t);if(!p)return JSON.stringify({error:"skill_not_found",message:`Skill "${t}" not found. Use skill.create to create it first.`},null,2);let m=(await H.readFile(p,"utf-8")).replace(/\r\n/g,`
470
+ `),u=Ja(m),f=u.tags?Va(u.tags):[],b=u.title||t,y=u.version||"1.0.0",w=o??b,v=c?[...new Set([...f,...c])]:f,C=new Date().toISOString();if(n!==void 0&&(m=m.replace(/## Description\n\n[\s\S]*?(?=\n## )/,`## Description
471
+
472
+ ${n}
473
+
474
+ `)),s!==void 0){let R=s.map(D=>`- "${D}"`).join(`
475
+ `);m=m.replace(/## Triggers\n\n[\s\S]*?(?=\n## )/,`## Triggers
476
+
477
+ ${R}
478
+
479
+ `)}if(i!==void 0&&(m=m.replace(/## Instructions\n\n[\s\S]*?(?=\n## |$)/,`## Instructions
480
+
481
+ ${i}
482
+
483
+ `)),a){let R=m.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if(R){let D=R[1]??"",M=D.trim()?`
484
+
485
+ `:"";m=m.replace(/## Examples\n\n[\s\S]*?(?=\n## |$)/,`## Examples
486
+
487
+ ${D}${M}${a}
488
+
489
+ `)}else m=m.trimEnd()+`
490
+
491
+ ## Examples
492
+
493
+ ${a}
494
+ `}m=m.replace(/^---\n[\s\S]*?\n---/,["---",`name: ${t}`,`title: ${w}`,`version: ${y}`,`updated: ${C}`,`tags: [${v.map(R=>`"${R}"`).join(", ")}]`,"---"].join(`
495
+ `)),await H.writeFile(p,m,"utf-8");let T=[];return o&&T.push("title"),n!==void 0&&T.push("description"),s!==void 0&&T.push("triggers"),i!==void 0&&T.push("instructions"),a&&T.push("examples (appended)"),c&&T.push(`tags (+${c.length})`),JSON.stringify({success:!0,skill:t,path:p,updated:T,message:`Skill "${t}" updated successfully`},null,2)}}}function Wv(r){return{name:"skill.list",displayName:"List Skills",description:"List all skills in the skill library, optionally filtered by tag.",category:"skills",parameters:{type:"object",properties:{tag:{type:"string",description:"Filter skills by tag (optional)."},verbose:{type:"boolean",description:"Include description and triggers in the output (default: false).",default:!1}},required:[]},async execute(e){let t=e.tag,o=e.verbose??!1;try{await H.access(r)}catch{return JSON.stringify({skills:[],count:0,message:"No skills directory found. Use skill.create to create your first skill."},null,2)}let n=await Iv(r);if(n.length===0)return JSON.stringify({skills:[],count:0,message:"No skills found. Use skill.create to create your first skill."},null,2);let s=[];for(let i of n){let a=(await H.readFile(i,"utf-8")).replace(/\r\n/g,`
496
+ `),c=Ja(a),p=c.name||te.basename(i,".skill.md"),m=c.title||p,u=c.tags?Va(c.tags):[];if(t&&!u.includes(t))continue;let f=te.dirname(te.relative(r,i)),b=f==="."?void 0:f.split(te.sep)[0];o?s.push({name:p,title:m,tags:u,category:b,description:ut(a,"Description")||void 0,triggers:Ka(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 Kw(r){let e=te.resolve(r?.dir??".toolpack/skills"),t=[jv(e),Fv(e),qv(e),Wv(e)];return{manifest:{key:"skill",name:"skill-tools",displayName:"Skill Management",version:"1.0.0",description:"Tools for creating, reading, updating, and listing agent skill files.",tools:["skill.create","skill.read","skill.update","skill.list"],category:"skills"},tools:t}}l();l();l();l();var us=`
362
497
  You are a planning assistant. Given a user request, create a detailed step-by-step plan.
363
498
 
364
499
  Rules:
@@ -384,26 +519,7 @@ Rules:
384
519
  }
385
520
  ]
386
521
  }
387
- `,Bn=`
388
- You are executing step {stepNumber} of a plan.
389
-
390
- Plan summary: {planSummary}
391
-
392
- Current step: {stepDescription}
393
-
394
- Previous steps completed:
395
- {previousStepsResults}
396
-
397
- Execute this step now. Use the available tools as needed to accomplish this specific step.
398
- Make reasonable assumptions if any details are ambiguous - do NOT ask the user for clarification or additional input.
399
- Produce concrete results based on the information available.
400
- If you cannot complete this step, explain why.
401
-
402
- IMPORTANT: Your response should be written as if you are directly answering the user.
403
- Do NOT mention steps, plans, workflow details, or internal process in your response.
404
- Do NOT say things like "Step 1 is complete" or "proceeding to the next step".
405
- Just provide the actual answer or result naturally.
406
- `,HT={name:"Direct",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}},fa={name:"Agent",planning:{enabled:!0,planningPrompt:Gn},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:Bn},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},wb=`
522
+ `,Uv={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},Qa={name:"Agent",planning:{enabled:!0,planningPrompt:us},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Jw=`
407
523
  Create a step-by-step plan for this coding task.
408
524
 
409
525
  Rules:
@@ -426,72 +542,32 @@ JSON Schema:
426
542
  }
427
543
  ]
428
544
  }
429
- `,Tb=`
430
- Execute step {stepNumber}: {stepDescription}
431
-
432
- Plan: {planSummary}
433
-
434
- Previous: {previousStepsResults}
435
-
436
- Use tools. Be concise. Show code changes clearly.
437
- No meta-commentary about steps or workflow.
438
- `,ga={name:"Coding",planning:{enabled:!0,planningPrompt:wb},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:Tb},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},ha={name:"Chat",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!1}};var ya={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:fa,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},ba={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:ha,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},wa={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:ga,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"]}},yr=[ya,wa,ba],et="chat";var wo=class{modes=new Map;orderedNames=[];constructor(){for(let e of yr)this.register(e)}register(e){if(!e.name||typeof e.name!="string")throw new Error("ModeConfig.name is required and must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("ModeConfig.displayName is required and must be a non-empty string");if(typeof e.systemPrompt!="string")throw new Error("ModeConfig.systemPrompt must be a string (can be empty for passthrough)");if(e.blockAllTools!==void 0&&typeof e.blockAllTools!="boolean")throw new Error("ModeConfig.blockAllTools must be a boolean");let t=["allowedToolCategories","blockedToolCategories","allowedTools","blockedTools"];for(let r of t)if(e[r]!==void 0&&!Array.isArray(e[r]))throw new Error(`ModeConfig.${r} must be an array`);let o=this.modes.has(e.name);this.modes.set(e.name,e),o||this.orderedNames.push(e.name)}get(e){return this.modes.get(e)}has(e){return this.modes.has(e)}getAll(){let e=[];for(let t of this.orderedNames){let o=this.modes.get(t);o&&e.push(o)}return e}getNames(){return[...this.orderedNames]}getDefault(){let e=this.modes.get(et);if(!e)throw new Error(`Default mode "${et}" not found in registry`);return e}getNext(e){let t=this.orderedNames.indexOf(e),o=t===-1?0:(t+1)%this.orderedNames.length,r=this.orderedNames[o],s=this.modes.get(r);if(!s)throw new Error(`Mode "${r}" not found in registry`);return s}get size(){return this.modes.size}remove(e){if(yr.some(r=>r.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(r=>r!==e)),o}};c();function xb(n){return{name:n.name,displayName:n.displayName,description:n.description||n.displayName,systemPrompt:n.systemPrompt,allowedToolCategories:n.allowedToolCategories||[],blockedToolCategories:n.blockedToolCategories||[],allowedTools:n.allowedTools||[],blockedTools:n.blockedTools||[],blockAllTools:n.blockAllTools||!1,baseContext:n.baseContext,workflow:n.workflow}}c();var zn={planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}};c();P();var KT=Gn,To=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||KT,r=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);h(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${r}..."`);let s=e.messages.filter(p=>p.role==="system"),i=e.messages.filter(p=>p.role!=="system"),a=[{role:"system",content:o},...s,...i],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 C(`[Planner] createPlan() succeeded plan.id=${m.id} steps=${m.steps.length}`),m}catch(p){return M(`[Planner] createPlan() failed, using fallback: ${p.message}`),this.createFallbackPlan(e)}}parsePlan(e,t,o){try{let r=JSON.parse(e);if(!r.summary||!Array.isArray(r.steps))throw new Error("Invalid plan structure: missing summary or steps array");let s=this.config?.maxSteps??20,i=r.steps.slice(0,s);r.steps.length>s&&M(`[Planner] parsePlan() truncated ${r.steps.length} steps to maxSteps=${s}`),h(`[Planner] parsePlan() parsed ${i.length} steps successfully`);let a=i.map((p,m)=>({id:`step-${Date.now()}-${m}`,number:p.number||m+1,description:p.description||"Unknown step",expectedTools:p.expectedTools||[],dependsOn:p.dependsOn||[],status:"pending"})),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:r.summary,steps:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(r){return M(`[Planner] parsePlan() failed: ${r.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){M("[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();c();var xo=class{static getProgress(e){let t=e.steps.length,o=e.steps.findIndex(l=>l.status!=="completed"&&l.status!=="skipped");o===-1&&(o=t);let r=t>0?Math.round(o/t*100):0,s=e.steps[o],i=s?s.description:"Done",a="executing";return e.status==="draft"&&(a="planning"),e.status==="approved"&&(a="executing"),e.status==="completed"&&(a="completed"),(e.status==="failed"||e.status==="cancelled")&&(a="failed"),{planId:e.id,currentStep:Math.min(o+1,t),totalSteps:t,percentage:r,currentStepDescription:i,status:a}}static summarizeCompletedSteps(e,t){let o=[];for(let r of e.steps){if(r.id===t)break;if(r.status==="completed"&&r.result){let s=r.result.toolsUsed?.length?` (Tools: ${r.result.toolsUsed.join(", ")})`:"",i=r.result.output||"No output";i.length>500&&(i=i.substring(0,500)+"... [truncated]"),o.push(`Step ${r.number}: ${r.description}${s}
439
- Result: ${i}`)}else r.status==="failed"?o.push(`Step ${r.number}: ${r.description}
440
- Failed: ${r.result?.error||"Unknown error"}`):r.status==="skipped"&&o.push(`Step ${r.number}: ${r.description}
441
- Skipped.`)}return o.length===0?"No previous steps.":o.join(`
442
-
443
- `)}};P();var JT=Bn,QT=`
444
- Based on the result of the previous step, do we need to add any new steps to our plan before continuing?
445
- Only add steps if they are absolutely necessary to complete the user's request.
446
-
447
- Already planned next steps:
448
- {{REMAINING_STEPS}}
449
-
450
- Only suggest steps if they are NOT covered by the above.
451
-
452
- If additional steps are truly required, respond with a JSON object containing the new steps.
453
- If not necessary or if the plan is sufficient, respond with {"steps": []}.
454
-
455
- JSON Schema:
456
- {
457
- "steps": [
458
- { "description": "What to do", "expectedTools": [] }
459
- ]
460
- }
461
- `,vo=class{client;config;constructor(e,t){this.client=e,this.config=t}async executeStep(e,t,o,r){let s=Date.now();h(`[StepExecutor] executeStep() step=${e.number} "${e.description}" expectedTools=${e.expectedTools?.join(",")||"none"}`);let i=this.buildStepRequest(e,t,o);try{let a=await this.client.generate(i,r),l=new Set;a.tool_calls&&a.tool_calls.forEach(m=>l.add(m.name));let p=Date.now()-s;return C(`[StepExecutor] Step ${e.number} completed in ${p}ms toolsUsed=[${Array.from(l).join(", ")||"none"}] output_len=${a.content?.length??0}`),{success:!0,output:a.content||"Step completed successfully.",toolsUsed:Array.from(l),duration:p,response:a}}catch(a){let l=Date.now()-s;return M(`[StepExecutor] Step ${e.number} failed in ${l}ms: ${a.message}`),{success:!1,error:a.message||"Unknown execution error",duration:l}}}async*streamStep(e,t,o,r){h(`[StepExecutor] streamStep() step=${e.number} "${e.description}"`);let s=this.buildStepRequest(e,t,o);yield*this.client.stream(s,r)}buildStepRequest(e,t,o){let r=xo.summarizeCompletedSteps(t,e.id),i=(this.config?.stepPrompt||JT).replace("{stepNumber}",e.number.toString()).replace("{planSummary}",t.summary).replace("{stepDescription}",e.description).replace("{previousStepsResults}",r),a=o.messages.filter(d=>d.role==="system"),l=o.messages.filter(d=>d.role!=="system"),p=[...a,...l],m=[];for(let d of t.steps){if(d.id===e.id)break;if(d.status==="completed"&&d.result?.output){let f=d.result.output;f.length>2e3&&(f=f.substring(0,2e3)+`
462
- ... [truncated]`),m.push({role:"assistant",content:f}),m.push({role:"user",content:`Step ${d.number} is complete. Now proceed with the next step.`})}}return{...o,messages:[{role:"system",content:i},...p,...m],tool_choice:"auto"}}async checkForDynamicSteps(e,t,o,r){if(!this.config?.allowDynamicSteps)return[];let s=t.steps.length,i=this.config.maxTotalSteps??50;if(s>=i)return h(`[StepExecutor] checkForDynamicSteps() skipped \u2014 already at maxTotalSteps=${i}`),[];h(`[StepExecutor] checkForDynamicSteps() after step=${e.number} currentTotal=${s} max=${i}`);let a=t.steps.filter(b=>b.status==="pending"&&b.number>e.number).map(b=>`${b.number}. ${b.description}`).join(`
463
- `)||"None",l=QT.replace("{{REMAINING_STEPS}}",a),p=o.messages.filter(b=>b.role==="system"),m=o.messages.filter(b=>b.role!=="system"),d=[...p,...m],f={...o,tool_choice:"none",response_format:"json_object",messages:[...d,{role:"assistant",content:e.result?.output||""},{role:"user",content:l}]};try{let b=await this.client.generate(f,r),y=JSON.parse(b.content||'{"steps": []}');if(Array.isArray(y.steps)&&y.steps.length>0){let w=i-s,T=y.steps.slice(0,w),S=new Set(t.steps.map(D=>this.normalizeStepDescription(D.description))),v=T.filter(D=>{let F=this.normalizeStepDescription(D.description||"");return S.has(F)?!1:(S.add(F),!0)});return v.length===0?(h("[StepExecutor] checkForDynamicSteps() all proposed steps were duplicates \u2014 skipping"),[]):(C(`[StepExecutor] checkForDynamicSteps() adding ${v.length} dynamic step(s) after step ${e.number}`),v.map((D,F)=>({id:`step-${Date.now()}-dyn-${F}`,number:0,description:D.description||"Dynamic step",expectedTools:D.expectedTools||[],dependsOn:[e.id],status:"pending"})))}}catch{}return[]}normalizeStepDescription(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim().split(" ").filter(t=>t.length>2).sort().join(" ")}};c();var vb=require("events");P();var br=class extends vb.EventEmitter{client;config;planner;stepExecutor;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new lt,this.planner=new To(e,t.planning),this.stepExecutor=new vo(e,t.steps)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new To(this.client,e.planning),this.stepExecutor=new vo(this.client,e.steps)}shouldRouteSimpleQuery(e){if(!this.config.complexityRouting?.enabled)return!1;let t=this.config.complexityRouting.strategy??"single-step";if(t==="disabled")return!1;let o=He(e.messages);if(!o)return!1;let r=this.queryClassifier.classify(o),s=this.config.complexityRouting.confidenceThreshold??.6,i=!1;switch(r.type){case"action":i=!1;break;case"conversational":i=!0;break;case"analytical":i=r.confidence>=s;break}return h(`[Workflow] shouldRouteSimpleQuery() type=${r.type} confidence=${r.confidence.toFixed(2)} threshold=${s} shouldRoute=${i} strategy=${t}`),i}async execute(e,t){if(this.shouldRouteSimpleQuery(e))return this.executeDirect(e,t);let o=this.config.planning?.enabled,r=this.config.steps?.enabled;if(h(`[Workflow] execute() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r)return h("[Workflow] execute() mode=direct"),this.executeDirect(e,t);let s=null;if(o){if(h("[Workflow] execute() mode=planning \u2014 creating plan"),s=await this.createPlan(e,t),this.emit("workflow:plan_created",s),this.config.planning?.requireApproval){C(`[Workflow] Plan "${s.id}" requires approval \u2014 waiting`),this.emitProgress(s,"awaiting_approval","Waiting for plan approval");let i=await this.waitForApproval(s.id);if(this.emit("workflow:plan_decision",s,i),!i)return C(`[Workflow] Plan "${s.id}" rejected by user`),s.status="cancelled",this.emitProgress(s,"failed","Plan rejected by user"),{success:!1,plan:s,error:"Plan rejected by user",metrics:{totalDuration:0,stepsCompleted:0,stepsFailed:0,retriesUsed:0}};C(`[Workflow] Plan "${s.id}" approved`)}s.status="approved"}return r?(s||(h("[Workflow] execute() mode=steps-only \u2014 creating implicit plan"),s=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",s),s.status="approved"),this.executeStepByStep(s,e,t)):s?(h("[Workflow] execute() mode=plan-direct (planning only, no steps)"),this.executePlanDirect(s,e,t)):this.executeDirect(e,t)}async executeDirect(e,t){let o=Date.now(),r=this.createDummyPlan(e);h(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(r,"executing","Direct execution");let s=await this.client.generate(e,t);r.status="completed",r.completedAt=new Date,r.steps[0].status="completed";let i=Date.now()-o;h(`[Workflow] executeDirect() completed in ${i}ms content_len=${s.content?.length??0}`);let a={success:!0,plan:r,output:s.content||void 0,metrics:{totalDuration:Date.now()-o,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",r,a),this.emitProgress(r,"completed","Done"),a}catch(s){r.status="failed",r.completedAt=new Date,r.steps[0].status="failed",M(`[Workflow] executeDirect() failed: ${s.message}`);let i={success:!1,plan:r,error:s.message,metrics:{totalDuration:Date.now()-o,stepsCompleted:0,stepsFailed:1,retriesUsed:0}};return this.emit("workflow:failed",r,s),this.emitProgress(r,"failed","Execution failed"),i}}async createPlan(e,t){h(`[Workflow] createPlan() provider=${t??"default"}`);let o=this.createDummyPlan(e);o.status="draft",this.emitProgress(o,"planning","Creating plan...");let r=await this.planner.createPlan(e,t);return C(`[Workflow] createPlan() completed plan.id=${r.id} steps=${r.steps.length}`),r}async executeStepByStep(e,t,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),C(`[Workflow] executeStepByStep() plan.id=${e.id} steps=${e.steps.length} maxRetries=${this.config.steps?.maxRetries??3}`);let r=Date.now(),s=0;for(let l=0;l<e.steps.length;l++){let p=e.steps[l];if(p.status!=="pending"&&p.status!=="failed")continue;if(p.dependsOn?.length){let y=p.dependsOn.filter(w=>{let T=e.steps.find(S=>S.id===String(w)||S.number===Number(w));return T?T.status!=="completed":!1});if(y.length>0){h(`[Workflow] Step ${p.number} skipped \u2014 unmet deps: ${y.join(", ")}`),p.status="skipped",p.result={success:!1,error:`Unmet dependencies: ${y.join(", ")}`};continue}}p.status="in_progress",this.emit("workflow:step_start",p,e),this.emitProgress(e,"executing",p.description),C(`[Workflow] Step ${p.number}/${e.steps.length} starting: "${p.description}"`);let m=0,d=this.config.steps?.maxRetries??3,f=null,b=!1;for(;m<=d;)try{let y=await this.stepExecutor.executeStep(p,e,t,o);if(y.success){p.status="completed",p.result=y,this.emit("workflow:step_complete",p,e),h(`[Workflow] Step ${p.number} completed in ${y.duration??0}ms toolsUsed=${(y.toolsUsed??[]).join(",")||"none"}`),b=!0;break}else throw new Error(y.error||"Step returned unsuccessful result")}catch(y){if(f=y,m++,m<=d&&this.config.steps?.retryOnFailure)s++,M(`[Workflow] Step ${p.number} failed (attempt ${m}/${d}), retrying: ${f.message}`),this.emit("workflow:step_retry",p,m,e),this.emitProgress(e,"executing",`[Retry ${m}] ${p.description}`);else{M(`[Workflow] Step ${p.number} failed permanently: ${f.message}`),p.status="failed",p.result={success:!1,error:f.message},this.emit("workflow:step_failed",p,f,e);break}}if(!b){let y=this.config.onFailure?.strategy||"abort";if(h(`[Workflow] Step ${p.number} failed \u2014 applying strategy="${y}"`),y==="abort"){e.status="failed",e.completedAt=new Date;let w={success:!1,plan:e,error:`Step ${p.number} failed: ${f?.message}`,metrics:this.computeMetrics(e,r,s)};return this.emit("workflow:failed",e,f),this.emitProgress(e,"failed","Workflow aborted due to step failure"),w}else if(y==="ask_user"){if(this.emitProgress(e,"awaiting_approval",`Step failed: ${f?.message}. Continue?`),!await this.waitForApproval(e.id)){e.status="failed",e.completedAt=new Date;let T={success:!1,plan:e,error:`Workflow aborted by user after step ${p.number} failure`,metrics:this.computeMetrics(e,r,s)};return this.emit("workflow:failed",e,new Error(T.error)),T}p.status="skipped"}else p.status="skipped"}if(b&&this.config.steps?.allowDynamicSteps){let y=await this.stepExecutor.checkForDynamicSteps(p,e,t,o);if(y.length>0){let w=p.number+1;for(let T of y)T.number=w++;for(let T=l+1;T<e.steps.length;T++)e.steps[T].number=w++;e.steps.splice(l+1,0,...y),y.forEach(T=>this.emit("workflow:step_added",T,e))}}}let i=this.computeMetrics(e,r,s);e.status="completed",e.completedAt=new Date,e.metrics=i,C(`[Workflow] executeStepByStep() completed plan.id=${e.id} duration=${i.totalDuration}ms stepsCompleted=${i.stepsCompleted} stepsFailed=${i.stepsFailed} retriesUsed=${s}`);let a={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};return this.emit("workflow:completed",e,a),this.emitProgress(e,"completed","Done"),a}async executePlanDirect(e,t,o){let r=Date.now();e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),this.emitProgress(e,"executing","Executing plan"),h(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
545
+ `,Xa={name:"Coding",planning:{enabled:!0,planningPrompt:Jw},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Ya={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var Za={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:Qa,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},el={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:Ya,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},tl={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:Xa,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"]}},sr=[Za,tl,el],ft="chat";var rn=class{modes=new Map;orderedNames=[];constructor(){for(let e of sr)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(ft);if(!e)throw new Error(`Default mode "${ft}" 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(sr.some(n=>n.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(n=>n!==e)),o}};l();function Vw(r){return{name:r.name,displayName:r.displayName,description:r.description||r.displayName,systemPrompt:r.systemPrompt,allowedToolCategories:r.allowedToolCategories||[],blockedToolCategories:r.blockedToolCategories||[],allowedTools:r.allowedTools||[],blockedTools:r.blockedTools||[],blockAllTools:r.blockAllTools||!1,baseContext:r.baseContext,workflow:r.workflow}}l();var fs={planning:{enabled:!1},progress:{enabled:!0}};l();k();var Gv=us,sn=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||Gv,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],c={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:a};try{let p=await this.client.generate(c,t),m=this.parsePlan(p.content||"",e,p);return P(`[Planner] createPlan() succeeded plan.id=${m.id} steps=${m.steps.length}`),m}catch(p){return 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"})),c=t.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}`,request:c,summary:n.summary,steps:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(n){return 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}}};l();var Qw=require("events");k();var ir=class extends Qw.EventEmitter{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new vt,this.planner=new sn(e,t.planning)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new sn(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=ot(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=`
464
546
  You have created the following plan to fulfill the request:
465
547
  Summary: ${e.summary}
466
548
 
467
549
  Steps:
468
- ${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
550
+ ${e.steps.map(c=>`${c.number}. ${c.description}`).join(`
469
551
  `)}
470
552
 
471
553
  Execute this plan now.
472
- `.trim(),i={...t,messages:[{role:"system",content:s},...t.messages]};try{let a=await this.client.generate(i,o);e.steps.forEach(p=>{p.status="completed",p.result={success:!0,output:a.content||""}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,r,0),h(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-r}ms`);let l={success:!0,plan:e,output:a.content||void 0,metrics:e.metrics};return this.emit("workflow:completed",e,l),this.emitProgress(e,"completed","Done"),l}catch(a){e.status="failed",e.completedAt=new Date,M(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${a.message}`);let l={success:!1,plan:e,error:a.message,metrics:this.computeMetrics(e,r,0)};return this.emit("workflow:failed",e,a),this.emitProgress(e,"failed","Execution failed"),l}}emitProgress(e,t,o){if(!this.config.progress?.enabled)return;let r=xo.getProgress(e);t&&(r.status=t),o&&(r.currentStepDescription=o),this.emit("workflow:progress",r)}computeMetrics(e,t,o){return{totalDuration:Date.now()-t,stepsCompleted:e.steps.filter(r=>r.status==="completed").length,stepsFailed:e.steps.filter(r=>r.status==="failed").length,retriesUsed:o}}summarizePlanResult(e){return`Workflow completed.
473
- Summary: ${e.summary}
474
- Steps:
475
- `+e.steps.map(t=>`[${t.status.toUpperCase()}] ${t.description}`).join(`
476
- `)}extractFinalOutput(e){let t=e.steps[e.steps.length-1];if(t&&/synthesize|summarize|consolidate|combine/i.test(t.description)&&e.steps.length>1)for(let r=e.steps.length-1;r>=0;r--){let s=e.steps[r];if(s.status==="completed"&&s.result?.output)return s.result.output}else{let r=[];for(let s of e.steps)s.status==="completed"&&s.result?.output&&r.push(s.result.output);if(r.length>0)return r.join(`
554
+ `.trim(),i=this.injectPlanContext(t.messages,s),a={...t,messages:i};try{let c=await this.client.generate(a,o);e.steps.forEach(m=>{m.status="completed",m.result={success:!0,output:c.content||"",response:c}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,n,0),h(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-n}ms`);let p={success:!0,plan:e,output:c.content||void 0,response:c,metrics:e.metrics};return this.emit("workflow:completed",e,p),this.emitProgress(e,"completed","Done"),p}catch(c){e.status="failed",e.completedAt=new Date,L(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${c.message}`);let p={success:!1,plan:e,error:c.message,metrics:this.computeMetrics(e,n,0)};return this.emit("workflow:failed",e,c),this.emitProgress(e,"failed","Execution failed"),p}}emitProgress(e,t,o,n){if(!this.config.progress?.enabled)return;let s=e.steps.length,i=e.steps.filter(p=>p.status==="completed"||p.status==="skipped").length,a=n??(s>0?Math.round(i/s*100):0),c={planId:e.id,currentStep:Math.min(i+1,s),totalSteps:s,percentage:a,currentStepDescription:o??e.steps[i]?.description??"Done",status:t??"executing"};this.emit("workflow:progress",c)}computeMetrics(e,t,o){return{totalDuration:Date.now()-t,stepsCompleted:e.steps.filter(n=>n.status==="completed").length,stepsFailed:e.steps.filter(n=>n.status==="failed").length,retriesUsed:o}}createDummyPlan(e){let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Object]").join(`
555
+ `);return{id:`plan-direct-${Date.now()}`,request:t,summary:"Direct execution",steps:[{id:"step-1",number:1,description:"Execute request",status:"pending",dependsOn:[],expectedTools:[]}],status:"in_progress",createdAt:new Date}}injectPlanContext(e,t){if(e[0]?.role==="system"){let n=e[0],s=typeof n.content=="string"?n.content:n.content.map(i=>i.text??"").join("");return[{...n,content:`${t}
477
556
 
478
- `)}return e.steps.length===0||e.steps.every(r=>r.status==="pending")?e.summary:this.summarizePlanResult(e)}extractFinalResponse(e){for(let t=e.steps.length-1;t>=0;t--){let o=e.steps[t];if(o.status==="completed"&&o.result?.response)return o.result.response}}createDummyPlan(e){let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Object]").join("\\n");return{id:`plan-direct-${Date.now()}`,request:t,summary:"Direct execution",steps:[{id:"step-1",number:1,description:"Execute request",status:"pending",dependsOn:[],expectedTools:[]}],status:"in_progress",createdAt:new Date}}async*stream(e,t){let o=this.config.planning?.enabled,r=this.config.steps?.enabled;if(h(`[Workflow] stream() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r){h("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}let s=null;if(o){if(yield{delta:"",workflowStep:{number:0,description:"Creating plan..."}},s=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",s),this.config.planning?.requireApproval){this.emitProgress(s,"awaiting_approval","Waiting for plan approval"),yield{delta:`
557
+ ---
558
+
559
+ ${s}`},...e.slice(1)]}return[{role:"system",content:t},...e]}async*stream(e,t){if(this.shouldRouteSimpleQuery(e)){h("[Workflow] stream() complexity-routed \u2192 direct"),yield*this.streamDirect(e,t);return}let o=this.config.planning?.enabled;if(h(`[Workflow] stream() planningEnabled=${o} provider=${t??"default"}`),!o){h("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}yield{delta:"",workflowStep:{number:0,description:"Creating plan..."}};let n=await this.planner.createPlan(e,t);if(this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){this.emitProgress(n,"awaiting_approval","Waiting for plan approval"),yield{delta:`
479
560
 
480
561
  **Plan Created:**
481
- ${s.summary}
562
+ ${n.summary}
482
563
 
483
564
  Steps:
484
- ${s.steps.map(a=>`${a.number}. ${a.description}`).join(`
565
+ ${n.steps.map(i=>`${i.number}. ${i.description}`).join(`
485
566
  `)}
486
567
 
487
- *Waiting for approval...*`,workflowStep:{number:0,description:"Awaiting approval"}};let i=await this.waitForApproval(s.id);if(this.emit("workflow:plan_decision",s,i),!i){s.status="cancelled",yield{delta:`
488
-
489
- *Plan rejected by user.*`,finish_reason:"stop"};return}}s.status="approved"}if(r){s||(s=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",s),s.status="approved"),yield*this.streamStepByStep(s,e,t);return}if(s){yield*this.streamPlanDirect(s,e,t);return}yield*this.streamDirect(e,t)}async*streamDirect(e,t){yield*this.client.stream(e,t)}async*streamStepByStep(e,t,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let r=Date.now(),s=0;for(let a=0;a<e.steps.length;a++){if(t.signal?.aborted){e.status="cancelled",e.completedAt=new Date,this.emit("workflow:failed",e,new Error("Interrupted by user"));return}let l=e.steps[a];if(l.status!=="pending"&&l.status!=="failed")continue;if(l.dependsOn?.length){let y=l.dependsOn.filter(w=>{let T=e.steps.find(S=>S.id===String(w)||S.number===Number(w));return T?T.status!=="completed":!1});if(y.length>0){l.status="skipped",l.result={success:!1,error:`Unmet dependencies: ${y.join(", ")}`};continue}}l.status="in_progress",this.emit("workflow:step_start",l,e),this.emitProgress(e,"executing",l.description);let p=0,m=this.config.steps?.maxRetries??3,d=null,f=!1,b="";for(;p<=m;)try{for await(let y of this.stepExecutor.streamStep(l,e,t,o)){if(t.signal?.aborted){l.status="skipped",e.status="cancelled",e.completedAt=new Date,this.emit("workflow:failed",e,new Error("Interrupted by user"));return}y.delta&&(b+=y.delta),yield{...y,workflowStep:{number:l.number,description:l.description}}}l.status="completed",l.result={success:!0,output:b,duration:Date.now()-r},this.emit("workflow:step_complete",l,e),this.emitProgress(e,"executing"),f=!0;break}catch(y){if(d=y,p++,p<=m&&this.config.steps?.retryOnFailure)s++,this.emit("workflow:step_retry",l,p,e),this.emitProgress(e,"executing",`[Retry ${p}/${m}] ${l.description}`);else{l.status="failed",l.result={success:!1,error:d.message},this.emit("workflow:step_failed",l,d,e);break}}if(!f){let y=this.config.onFailure?.strategy||"abort";if(y==="abort"){e.status="failed",e.completedAt=new Date,this.emit("workflow:failed",e,d),yield{delta:`
568
+ *Waiting for approval...*`,workflowStep:{number:0,description:"Awaiting approval"}};let s=await this.waitForApproval(n.id);if(this.emit("workflow:plan_decision",n,s),!s){n.status="cancelled",yield{delta:`
490
569
 
491
- **Step failed:** ${d?.message}
492
- *Workflow aborted.*`,finish_reason:"stop"};return}else y==="skip"&&(l.status="skipped",yield{delta:`
493
- *Step skipped due to failure.*
494
- `,workflowStep:{number:l.number,description:l.description}})}if(f&&this.config.steps?.allowDynamicSteps){let y=await this.stepExecutor.checkForDynamicSteps(l,e,t,o);if(y.length>0){let w=l.number+1;for(let T of y)T.number=w++;for(let T=a+1;T<e.steps.length;T++)e.steps[T].number=w++;e.steps.splice(a+1,0,...y),y.forEach(T=>this.emit("workflow:step_added",T,e)),this.emitProgress(e,"executing")}}}e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,r,s);let i={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};this.emit("workflow:completed",e,i),this.emitProgress(e,"completed","Done"),yield{delta:"",finish_reason:"stop"}}async*streamPlanDirect(e,t,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let r=`
570
+ *Plan rejected by user.*`,finish_reason:"stop"};return}}n.status="approved",yield*this.streamPlanDirect(n,e,t)}async*streamDirect(e,t){yield*this.client.stream(e,t)}async*streamPlanDirect(e,t,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let n=`
495
571
  You have created the following plan to fulfill the request:
496
572
  Summary: ${e.summary}
497
573
 
@@ -500,7 +576,7 @@ ${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
500
576
  `)}
501
577
 
502
578
  Execute this plan now.
503
- `.trim(),s={...t,messages:[{role:"system",content:r},...t.messages]},i="";for await(let a of this.client.stream(s,o))a.delta&&(i+=a.delta),yield a;e.steps.forEach(a=>{a.status="completed",a.result={success:!0,output:i}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:i,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)})}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};c();var Ta=require("events");P();var xa=class n extends Ta.EventEmitter{client;activeProviderName;modeRegistry;workflowExecutor;knowledgeLayers=[];customProviderNames=new Set;mcpToolProject=null;constructor(e,t,o){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=o;let r=this.client.getProvider(t);r&&this.forwardEvents(r),this.workflowExecutor=new br(this.client,zn,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 r of t)o.set(r.name,r);return{...e,requestTools:Array.from(o.values())}}static async init(e){let t=Go(e.configPath);La(t.logging);let o=new yo,r=so(e.configPath);o.setConfig(r),e.tools&&await o.loadBuiltIn(),e.customTools&&await o.loadProjects(e.customTools);let s=null,i=e.mcp||t.mcp;if(i)try{C("[MCP] Initializing MCP tool integration");let $=await Wn(i);s=$,await o.loadProjects([$]),C(`[MCP] Loaded ${$.tools.length} tools from MCP servers`)}catch($){oe(`[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[$,_]of Object.entries(e.providers)){let E=$===f,U=await n.createProvider($,_,e.configPath,!E);U&&(m[$]=U)}else if(e.provider){let $={apiKey:e.apiKey,model:e.model},_=await n.createProvider(e.provider,$,e.configPath,!1);_&&(m[e.provider]=_)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let $=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([_,E])=>(E.name=E.name||_,E));for(let _ of $){if(typeof _.generate!="function"||typeof _.stream!="function"||typeof _.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let E=_.name;if(!E)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[E])throw new Error(`Custom provider name "${E}" conflicts with a built-in provider designation. Choose a different name.`);d.add(E),m[E]=_}}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 wo;if(e.customModes)for(let $ of e.customModes)b.register($);let y={...p,...e.modeOverrides||{}};for(let[$,_]of Object.entries(y)){let E=b.get($);if(E){_.systemPrompt!==void 0&&(E.systemPrompt=_.systemPrompt),_.toolSearch&&(E.toolSearch={...E.toolSearch||{},..._.toolSearch});for(let[U,Y]of Object.entries(_))U!=="systemPrompt"&&U!=="toolSearch"&&(E[U]=Y)}}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 T=new Mo({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}),S=new n(T,f,b),v=e.knowledge,D=v==null?[]:Array.isArray(v)?v:[v];S.knowledgeLayers=D.filter($=>!!$&&typeof $.toTool=="function"),S.customProviderNames=d,S.mcpToolProject=s;let F=e.defaultMode||et,k=b.get(F);return k&&(T.setMode(k),k.workflow&&S.workflowExecutor.setConfig(k.workflow)),S}static async createProvider(e,t,o,r=!1){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(r)return null;throw new Error(`No API key found for '${e}'. Set ${s} or pass apiKey in config.`)}switch(e){case"openai":return new Qe(i,t.baseUrl);case"anthropic":return new Ao(i,t.baseUrl);case"gemini":return new Oo(i);case"openrouter":return new Fo(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new mt({baseUrl:t.baseUrl||jo(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||jo(o);return new Ne({model:s,baseUrl:i})}throw new Error(`Unknown provider type: ${e}`)}async generate(e,t){let o;typeof e=="string"?o={messages:[{role:"user",content:e}],model:""}:o=e,o=this.prepareRequest(o);let r=this.getMode();if(r?.workflow?.planning?.enabled||r?.workflow?.steps?.enabled){let s=await this.workflowExecutor.execute(o,t||this.activeProviderName),i=0,a=0,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.client.generate(o,t)}async*stream(e,t){let o=this.prepareRequest(e),r=this.getMode(),s=t||this.activeProviderName;if(r?.workflow?.planning?.enabled||r?.workflow?.steps?.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||Je();if(t)try{let o=Lo(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){M(`[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 Un(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[o,r]of e.entries()){let s=this.customProviderNames.has(o),i=[];try{i=await r.getModels()}catch(a){M(`[Toolpack] Failed to fetch models for provider '${o}': ${a}`)}t.push({name:o,displayName:r.getDisplayName(),type:s?"custom":"built-in",models:i})}return t}async loadToolProject(e){let t=this.client.getToolRegistry();if(t)await t.loadProject(e);else throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.")}async listModels(){let e=await this.listProviders(),t=[];for(let o of e)for(let r of o.models)t.push({...r,provider:o.name});return t}setMode(e){let t=this.modeRegistry.get(e);if(!t)throw new Error(`Mode "${e}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return this.client.setMode(t),t.workflow?this.workflowExecutor.setConfig(t.workflow):this.workflowExecutor.setConfig(zn),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 Ta.EventEmitter&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:step_start",(t,o)=>this.emit("workflow:step_start",t,o)),e.on("workflow:step_complete",(t,o)=>this.emit("workflow:step_complete",t,o)),e.on("workflow:step_failed",(t,o,r)=>this.emit("workflow:step_failed",t,o,r)),e.on("workflow:step_retry",(t,o,r)=>this.emit("workflow:step_retry",t,o,r)),e.on("workflow:step_added",(t,o)=>this.emit("workflow:step_added",t,o)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,o)=>this.emit("workflow:completed",t,o)),e.on("workflow:failed",(t,o)=>this.emit("workflow:failed",t,o))}};c();c();c();var Hn=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 Kn=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new Hn(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,r)=>o.timestamp.localeCompare(r.timestamp)),t.length>this.maxMessagesPerConversation&&t.splice(0,t.length-this.maxMessagesPerConversation))}async get(e,t={}){let r=(this.lru.get(e)??[]).slice();if(t.scope!==void 0&&(r=r.filter(s=>s.scope===t.scope)),t.sinceTimestamp!==void 0&&(r=r.filter(s=>s.timestamp>=t.sinceTimestamp)),t.participantIds!==void 0&&t.participantIds.length>0){let s=new Set(t.participantIds);r=r.filter(i=>s.has(i.participant.id))}return t.limit!==void 0&&r.length>t.limit&&(r=r.slice(r.length-t.limit)),r}async search(e,t,o={}){let r=this.lru.get(e)??[],s=t.toLowerCase(),i=o.limit??10,a=o.tokenCap??2e3,l=r.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 r=new Set(t),s=o.filter(i=>!r.has(i.id));this.lru.set(e,s)}clearConversation(e){this.lru.set(e,[])}get conversationCount(){return this.lru.size}};c();var Cb=x(require("better-sqlite3"),1),Co=x(require("fs"),1),wr=x(require("path"),1);function VT(){let n=wr.join(process.cwd(),".toolpack","db","conversation");return Co.existsSync(n)||Co.mkdirSync(n,{recursive:!0}),wr.join(n,"conversation.sqlite")}var Jn=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??VT(),o=wr.dirname(t);if(Co.existsSync(o)||Co.mkdirSync(o,{recursive:!0}),this.db=new Cb.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(`
579
+ `.trim(),s={...t,messages:this.injectPlanContext(t.messages,n)},i="";for await(let a of this.client.stream(s,o))a.delta&&(i+=a.delta),yield a;e.steps.forEach(a=>{a.status="completed",a.result={success:!0,output:i}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:i,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)}),this.emitProgress(e,"completed","Done")}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};l();var ol=require("events");k();var nl=class r extends ol.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 ir(this.client,fs,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}buildKnowledgeRequestTools(){return this.knowledgeLayers.length===0?[]:this.knowledgeLayers.length===1?[this.knowledgeLayers[0].toTool(),{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async s=>({success:!0,id:await this.knowledgeLayers[0].add(s.content,s.metadata),message:"Content added to knowledge base successfully."})}]:[{name:"knowledge_search",displayName:"Knowledge Search",description:`Search across ${this.knowledgeLayers.length} knowledge layers for relevant information.`,category:"search",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Search query to find relevant information"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"},threshold:{type:"number",description:"Minimum similarity threshold 0-1 (default: 0.7)"},filter:{type:"object",description:"Optional metadata filters"}},required:["query"]},execute:async o=>{let s=(await Promise.all(this.knowledgeLayers.map(async(a,c)=>(await a.toTool().execute({query:o.query,limit:o.limit,threshold:o.threshold,filter:o.filter})).map(u=>({...u,_layer:c}))))).flat();s.sort((a,c)=>(c.score??0)-(a.score??0));let i=o.limit??10;return s.slice(0,i)}},{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the primary knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async o=>({success:!0,id:await this.knowledgeLayers[0].add(o.content,o.metadata),message:"Content added to knowledge base successfully."})}]}prepareRequest(e){let t=[...this.buildKnowledgeRequestTools(),...e.requestTools||[]];if(t.length===0)return e;let o=new Map;for(let n of t)o.set(n.name,n);return{...e,requestTools:Array.from(o.values())}}static async init(e){let t=En(e.configPath);Tl(t.logging);let o=new on,n=Po(e.configPath);o.setConfig(n),e.tools&&await o.loadBuiltIn(),e.customTools&&await o.loadProjects(e.customTools);let s=null,i=e.mcp||t.mcp;if(i)try{P("[MCP] Initializing MCP tool integration");let S=await ms(i);s=S,await o.loadProjects([S]),P(`[MCP] Loaded ${S.tools.length} tools from MCP servers`)}catch(S){pe(`[MCP] Failed to initialize MCP tools: ${S}`)}let a=t.systemPrompt,c=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},u=new Set,f=e.defaultProvider||e.provider;if(e.providers)for(let[S,$]of Object.entries(e.providers)){let _=S===f,j=await r.createProvider(S,$,e.configPath,!_);j&&(m[S]=j)}else if(e.provider){let S={apiKey:e.apiKey,model:e.model,projectId:e.projectId,location:e.location,googleAuthOptions:e.googleAuthOptions},$=await r.createProvider(e.provider,S,e.configPath,!1);$&&(m[e.provider]=$)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let S=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([$,_])=>(_.name=_.name||$,_));for(let $ of S){if(typeof $.generate!="function"||typeof $.stream!="function"||typeof $.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let _=$.name;if(!_)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(m[_])throw new Error(`Custom provider name "${_}" conflicts with a built-in provider designation. Choose a different name.`);u.add(_),m[_]=$}}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 rn;if(e.customModes)for(let S of e.customModes)b.register(S);let y={...p,...e.modeOverrides||{}};for(let[S,$]of Object.entries(y)){let _=b.get(S);if(_){$.systemPrompt!==void 0&&(_.systemPrompt=$.systemPrompt),$.toolSearch&&(_.toolSearch={..._.toolSearch||{},...$.toolSearch});for(let[j,Ee]of Object.entries($))j!=="systemPrompt"&&j!=="toolSearch"&&(_[j]=Ee)}}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 v=new bn({providers:m,defaultProvider:f,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:a,disableBaseContext:c,hitlConfig:Object.keys(w).length>0?w:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow}),C=new r(v,f,b),T=e.knowledge,R=T==null?[]:Array.isArray(T)?T:[T];C.knowledgeLayers=R.filter(S=>!!S&&typeof S.toTool=="function"),C.customProviderNames=u,C.mcpToolProject=s,C._interceptors=e.interceptors??[];for(let S of C._interceptors)S.init&&await S.init();let D=e.defaultMode||ft,M=b.get(D);return M&&(v.setMode(M),M.workflow&&C.workflowExecutor.setConfig(M.workflow)),C}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new xn({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 st(i,t.baseUrl);case"anthropic":return new Tn(i,t.baseUrl);case"gemini":return new vn(i);case"openrouter":return new Sn(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new Pt({baseUrl:t.baseUrl||Pn(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||Pn(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,c=0,p={steps:[]};s.plan.planningResponse?.usage&&(i+=s.plan.planningResponse.usage.prompt_tokens,a+=s.plan.planningResponse.usage.completion_tokens||0,c+=s.plan.planningResponse.usage.total_tokens,p.planning=s.plan.planningResponse.usage);for(let u of s.plan.steps)if(u.status==="completed"&&u.result?.response?.usage){let f=u.result.response.usage;i+=f.prompt_tokens,a+=f.completion_tokens||0,c+=f.total_tokens,p.steps.push({stepNumber:u.number,description:u.description,usage:f})}let m={prompt_tokens:i,completion_tokens:a,total_tokens:c};return s.response?{...s.response,content:s.output||s.response.content||null,usage:m,usage_details:p}:{content:s.output||null,usage:m,usage_details:p}}return this._interceptors.length>0?this._buildInterceptorChain(this._interceptors,i=>this.client.generate(i??o,t))(o):this.client.generate(o,t)}_buildInterceptorChain(e,t){return e.reduceRight((o,n)=>s=>n(s,i=>o(i??s)),t)}async*stream(e,t){let o=this.prepareRequest(e),n=this.getMode(),s=t||this.activeProviderName;if(n?.workflow?.planning?.enabled){yield*this.workflowExecutor.stream(o,s);return}yield*this.client.stream(o,t)}async embed(e,t){return this.client.embed(e,t)}setProvider(e){let t=this.client.getProvider(e);this.activeProviderName=e,this.client.setDefaultProvider(e),this.forwardEvents(t)}getProvider(){return this.client.getProvider(this.activeProviderName)}getClient(){return this.client}reloadConfig(e){let t=e||rt();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 ds(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(fs),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 ol.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))}};l();l();l();var gs=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 hs=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new gs(e.maxConversations??500),this.maxMessagesPerConversation=e.maxMessagesPerConversation??500}async append(e){let t=this.lru.get(e.conversationId);t||(t=[],this.lru.set(e.conversationId,t)),!t.some(o=>o.id===e.id)&&(t.push(e),t.sort((o,n)=>o.timestamp.localeCompare(n.timestamp)),t.length>this.maxMessagesPerConversation&&t.splice(0,t.length-this.maxMessagesPerConversation))}async get(e,t={}){let n=(this.lru.get(e)??[]).slice();if(t.scope!==void 0&&(n=n.filter(s=>s.scope===t.scope)),t.sinceTimestamp!==void 0&&(n=n.filter(s=>s.timestamp>=t.sinceTimestamp)),t.participantIds!==void 0&&t.participantIds.length>0){let s=new Set(t.participantIds);n=n.filter(i=>s.has(i.participant.id))}return t.limit!==void 0&&n.length>t.limit&&(n=n.slice(n.length-t.limit)),n}async search(e,t,o={}){let n=this.lru.get(e)??[],s=t.toLowerCase(),i=o.limit??10,a=o.tokenCap??2e3,c=n.filter(u=>u.content.toLowerCase().includes(s)).slice().reverse(),p=[],m=0;for(let u of c){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}};l();var Xw=x(require("better-sqlite3"),1),an=x(require("fs"),1),ar=x(require("path"),1);function Bv(){let r=ar.join(process.cwd(),".toolpack","db","conversation");return an.existsSync(r)||an.mkdirSync(r,{recursive:!0}),ar.join(r,"conversation.sqlite")}var ys=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??Bv(),o=ar.dirname(t);if(an.existsSync(o)||an.mkdirSync(o,{recursive:!0}),this.db=new Xw.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(`
504
580
  CREATE TABLE IF NOT EXISTS messages (
505
581
  id TEXT NOT NULL,
506
582
  conversation_id TEXT NOT NULL,
@@ -515,7 +591,7 @@ Execute this plan now.
515
591
  )`),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_conv_ts ON messages (conversation_id, timestamp)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_conv_scope_ts ON messages (conversation_id, scope, timestamp)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_conv_participant_ts ON messages (conversation_id, participant_id, timestamp)"),this.useFTS&&(this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(doc_key UNINDEXED, content, tokenize = 'unicode61')"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_fts_key ON messages_fts (doc_key)"))}async append(e){let t=this.db.prepare(`INSERT OR IGNORE INTO messages (
516
592
  id, conversation_id, participant_kind, participant_id, participant_display_name,
517
593
  content, timestamp, scope, metadata
518
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),o=e.metadata?JSON.stringify(e.metadata):null,r=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&&r.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(T=>`${e.conversationId}:${T}`),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 = ?"],r=[e];if(t.scope!==void 0&&(o.push("scope = ?"),r.push(t.scope)),t.sinceTimestamp!==void 0&&(o.push("timestamp >= ?"),r.push(t.sinceTimestamp)),t.participantIds&&t.participantIds.length>0){let p=t.participantIds.map(()=>"?").join(",");o.push(`participant_id IN (${p})`),r.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(r).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 r=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
594
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),o=e.metadata?JSON.stringify(e.metadata):null,n=t.run(e.id,e.conversationId,e.participant.kind,e.participant.id,e.participant.displayName??null,e.content,e.timestamp,e.scope,o);if(this.useFTS&&n.changes>0){let s=`${e.conversationId}:${e.id}`;this.db.prepare("INSERT INTO messages_fts (doc_key, content) VALUES (?, ?)").run(s,e.content)}if(this.maxMessagesPerConversation>0){let a=this.db.prepare("SELECT COUNT(1) as c FROM messages WHERE conversation_id = ?").get(e.conversationId)?.c??0;if(a>this.maxMessagesPerConversation){let c=a-this.maxMessagesPerConversation,m=this.db.prepare("SELECT id FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC LIMIT ?").all(e.conversationId,c).map(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(v=>`${e.conversationId}:${v}`),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`,c=this.db.prepare(i).all(n).map(p=>this.rowToMessage(p));return t.limit!==void 0&&c.length>t.limit&&(c=c.slice(c.length-t.limit)),c}async search(e,t,o={}){let n=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
519
595
  SELECT m.id, m.conversation_id, m.participant_kind, m.participant_id, m.participant_display_name,
520
596
  m.content, m.timestamp, m.scope, m.metadata
521
597
  FROM messages m
@@ -526,4 +602,19 @@ Execute this plan now.
526
602
  content, timestamp, scope, metadata
527
603
  FROM messages
528
604
  WHERE conversation_id = ? AND content LIKE ? COLLATE NOCASE
529
- 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>=r)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 Pb=x(require("os"),1),tt=x(require("path"),1),Po=x(require("fs"),1),va=".toolpack",Ca="config",Pa="toolpack.config.json";function Sb(){return Pb.homedir()}function kb(){return tt.join(Sb(),va)}function Sa(){return tt.join(kb(),Ca)}function Tr(){return tt.join(Sa(),Pa)}function Rb(n=process.cwd()){return tt.join(n,va)}function ka(n=process.cwd()){return tt.join(Rb(n),Ca)}function xr(n=process.cwd()){return tt.join(ka(n),Pa)}function Ra(){let n=Sa();Po.existsSync(n)||Po.mkdirSync(n,{recursive:!0})}function XT(n=process.cwd()){let e=ka(n);Po.existsSync(e)||Po.mkdirSync(e,{recursive:!0})}c();var X=x(require("fs"),1),Qn=x(require("path"),1);function _a(n,e){if(!e)return n;if(!n)return e;let t={...n};for(let o of Object.keys(e))e[o]instanceof Array?t[o]=e[o]:e[o]instanceof Object&&o in n?t[o]=_a(n[o],e[o]):t[o]=e[o];return t}function $a(n){if(!X.existsSync(n))return null;try{let e=X.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}function YT(n=process.cwd()){let e=Qn.join(n,"toolpack.config.json"),t=Tr(),o=xr(n),r=$a(e)||{},s=$a(t)||{},i=$a(o)||{},a=_a(r,s);return a=_a(a,i),a}function ZT(n=process.cwd()){let e=Qn.join(n,"toolpack.config.json"),t=Tr(),o=xr(n),r=!X.existsSync(t),s=null,i="default";return X.existsSync(o)?(s=o,i="local"):X.existsSync(t)?(s=t,i="global"):X.existsSync(e)&&(s=e,i="base"),{isFirstRun:r,activeConfigPath:s,configSource:i}}function ex(n=process.cwd()){let e=Tr();if(!X.existsSync(e)){Ra();let t=null,o=xr(n);if(X.existsSync(o))t=o;else{let s=Qn.join(n,"toolpack.config.json");if(X.existsSync(s))t=s;else{let i=Je();i&&X.existsSync(i)&&(t=i)}}let r={};if(t)try{let s=X.readFileSync(t,"utf-8");r=JSON.parse(s)}catch{}X.writeFileSync(e,JSON.stringify(r,null,4),"utf-8")}}c();0&&(module.exports={AGENT_MODE,AGENT_PLANNING_PROMPT,AGENT_STEP_PROMPT,AGENT_WORKFLOW,AIClient,AnthropicAdapter,AuthenticationError,BM25SearchEngine,BUILT_IN_MODES,CHAT_MODE,CHAT_WORKFLOW,CODING_MODE,CODING_PLANNING_PROMPT,CODING_STEP_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,StepExecutor,SummarizationError,TOOLPACK_DIR_NAME,TOOL_SEARCH_NAME,TimeoutError,ToolDiscoveryCache,ToolRegistry,ToolRouter,Toolpack,WorkflowExecutor,addBypassRule,buildSummarizedHistory,cloudDeployTool,cloudListTool,cloudStatusTool,cloudToolsProject,codingFindSymbolTool,codingGetImportsTool,codingGetSymbolsTool,codingToolsProject,countTokens,createContextWindowStateManager,createMcpToolProject,createMode,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,fsCopyTool,fsCreateDirTool,fsDeleteFileTool,fsExistsTool,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,gitCommitTool,gitDiffTool,gitLogTool,gitStatusTool,gitToolsProject,githubContentsGetTextTool,githubGraphqlExecuteTool,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,systemCwdTool,systemDiskUsageTool,systemEnvTool,systemInfoTool,systemSetEnvTool,systemToolsProject,toDataUri,toolSearchDefinition,truncateMessage,validateSummarizationResult,webExtractLinksTool,webFetchTool,webScrapeTool,webSearchTool,webToolsProject,wouldExceedContextWindow});
605
+ ORDER BY timestamp DESC`).all(e,`%${t}%`);let a=i.map(m=>this.rowToMessage(m)),c=[],p=0;for(let m of a){if(c.length>=n)break;let u=Math.ceil(m.content.length/4);if(c.length>0&&p+u>s)break;c.push(m),p+=u}return c}async deleteMessages(e,t){if(!t||t.length===0)return;let o=t.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${o})`).run(e,...t),this.useFTS){let s=t.map(c=>`${e}:${c}`),i=s.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${i})`).run(...s)}}clearConversation(e){this.useFTS&&this.db.prepare("DELETE FROM messages_fts WHERE doc_key LIKE ?").run(`${e}:%`),this.db.prepare("DELETE FROM messages WHERE conversation_id = ?").run(e)}rowToMessage(e){return{id:e.id,conversationId:e.conversation_id,participant:{kind:e.participant_kind,id:e.participant_id,displayName:e.participant_display_name??void 0},content:e.content,timestamp:e.timestamp,scope:e.scope,metadata:e.metadata?JSON.parse(e.metadata):void 0}}close(){try{this.db.close()}catch{}}};l();var Yw=x(require("os"),1),gt=x(require("path"),1),ln=x(require("fs"),1),rl=".toolpack",sl="config",il="toolpack.config.json";function Zw(){return Yw.homedir()}function eT(){return gt.join(Zw(),rl)}function al(){return gt.join(eT(),sl)}function lr(){return gt.join(al(),il)}function tT(r=process.cwd()){return gt.join(r,rl)}function ll(r=process.cwd()){return gt.join(tT(r),sl)}function cr(r=process.cwd()){return gt.join(ll(r),il)}function cl(){let r=al();ln.existsSync(r)||ln.mkdirSync(r,{recursive:!0})}function zv(r=process.cwd()){let e=ll(r);ln.existsSync(e)||ln.mkdirSync(e,{recursive:!0})}l();var oe=x(require("fs"),1),bs=x(require("path"),1);function ml(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]=ml(r[o],e[o]):t[o]=e[o];return t}function pl(r){if(!oe.existsSync(r))return null;try{let e=oe.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function Hv(r=process.cwd()){let e=bs.join(r,"toolpack.config.json"),t=lr(),o=cr(r),n=pl(e)||{},s=pl(t)||{},i=pl(o)||{},a=ml(n,s);return a=ml(a,i),a}function Kv(r=process.cwd()){let e=bs.join(r,"toolpack.config.json"),t=lr(),o=cr(r),n=!oe.existsSync(t),s=null,i="default";return oe.existsSync(o)?(s=o,i="local"):oe.existsSync(t)?(s=t,i="global"):oe.existsSync(e)&&(s=e,i="base"),{isFirstRun:n,activeConfigPath:s,configSource:i}}function Jv(r=process.cwd()){let e=lr();if(!oe.existsSync(e)){cl();let t=null,o=cr(r);if(oe.existsSync(o))t=o;else{let s=bs.join(r,"toolpack.config.json");if(oe.existsSync(s))t=s;else{let i=rt();i&&oe.existsSync(i)&&(t=i)}}let n={};if(t)try{let s=oe.readFileSync(t,"utf-8");n=JSON.parse(s)}catch{}oe.writeFileSync(e,JSON.stringify(n,null,4),"utf-8")}}l();l();l();var Xe=x(require("fs/promises"),1),cn=x(require("path"),1);l();var Vv=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"]),ws=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=>!Vv.has(o))}addDocument(e,t){this.documents.set(e,t);let o=this.tokenize(t);this.documentLengths.set(e,o.length);let n={};for(let s of o)n[s]=(n[s]??0)+1;for(let[s,i]of Object.entries(n))this.termFrequencies.has(s)||this.termFrequencies.set(s,new Map),this.termFrequencies.get(s).set(e,i);this.updateAvgDocLength()}clear(){this.documents.clear(),this.termFrequencies.clear(),this.documentLengths.clear(),this.avgDocLength=0}get size(){return this.documents.size}updateAvgDocLength(){if(this.documentLengths.size===0){this.avgDocLength=0;return}let e=0;this.documentLengths.forEach(t=>{e+=t}),this.avgDocLength=e/this.documentLengths.size}idf(e){let t=this.documents.size,o=this.termFrequencies.get(e)?.size??0;return o===0?0:Math.log((t-o+.5)/(o+.5)+1)}search(e,t=10){let o=this.tokenize(e);if(o.length===0)return[];let n={};this.documents.forEach((i,a)=>{let c=0,p=this.documentLengths.get(a)??0;for(let m of o){let 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));c+=b*(y/w)}c>0&&(n[a]=c)});let s=Object.entries(n).map(([i,a])=>({id:i,score:a}));return s.sort((i,a)=>a.score-i.score),s.slice(0,t)}};l();var Qe=x(require("path"),1);function oT(r,e,t){let o=r.match(/^---\n([\s\S]*?)\n---/),n="",s="",i,a=[];if(o&&o[1]){let R=o[1].split(`
606
+ `);for(let D of R){let M=D.indexOf(":");if(M===-1)continue;let S=D.substring(0,M).trim(),$=D.substring(M+1).trim();if(S==="name"&&(n=$),S==="title"&&(s=$),S==="version"&&(i=$),S==="tags"){let _=$.match(/\[(.*)\]/);_&&_[1]&&(a=_[1].split(",").map(j=>j.trim().replace(/"/g,"")).filter(Boolean))}}}n||(n=Qe.basename(e,".skill.md"));let c=r.match(/## Description\n\n([\s\S]*?)(?=\n## |$)/),p=c&&c[1]?c[1].trim():"",m=r.match(/## Triggers\n\n([\s\S]*?)(?=\n## |$)/),u=[];if(m&&m[1]){let R=m[1].split(`
607
+ `).filter(D=>D.startsWith("- "));for(let D of R){let M=D.match(/^- "(.*)"/);M&&M[1]&&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,v=Qe.relative(t,e),C=Qe.dirname(v),T=C==="."?void 0:C.split(Qe.sep)[0];return{name:n,title:s,version:i,tags:a,category:T,filePath:e,description:p,triggers:u,instructions:b,examples:w||void 0,lastModified:0}}l();l();var B={name:50,title:100,tags:{count:10,each:30},description:300,triggers:{count:10,min:1,each:100},instructions:2e3,examples:3e3};var Qv=/^[a-z][a-z0-9-]*$/;function nT(r,e){let t=[],o=[];r.name?(Qv.test(r.name)||t.push(`name "${r.name}" must match kebab-case pattern /^[a-z][a-z0-9-]*$/`),r.name.length>B.name&&o.push(`name exceeds ${B.name} character limit (${r.name.length} chars)`)):t.push("name is required in frontmatter"),r.title?r.title.length>B.title&&o.push(`title exceeds ${B.title} character limit (${r.title.length} chars)`):t.push("title is required in frontmatter"),r.tags.length>B.tags.count&&o.push(`too many tags (${r.tags.length}); maximum is ${B.tags.count}`);for(let n of r.tags)n.length>B.tags.each&&o.push(`tag "${n}" exceeds ${B.tags.each} character limit`);if(r.description?r.description.length>B.description&&o.push(`description exceeds ${B.description} character limit (${r.description.length} chars)`):t.push("## Description section is required and must not be empty"),!r.triggers||r.triggers.length===0)t.push("## Triggers section must contain at least one trigger");else{r.triggers.length>B.triggers.count&&o.push(`too many triggers (${r.triggers.length}); maximum is ${B.triggers.count}`);for(let n of r.triggers)n.length>B.triggers.each&&o.push(`trigger "${n.substring(0,50)}..." exceeds ${B.triggers.each} character limit`)}return r.instructions?r.instructions.length>B.instructions&&o.push(`instructions exceed ${B.instructions} character limit (${r.instructions.length} chars)`):t.push("## Instructions section is required and must not be empty"),r.examples&&r.examples.length>B.examples&&o.push(`examples exceed ${B.examples} character limit (${r.examples.length} chars)`),{file:e,errors:t,warnings:o}}var Ts=class{dir;onValidationError;loaded=!1;skills=new Map;fileMtimes=new Map;index=new ws;_buildPromise=null;constructor(e){this.dir=cn.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=cn.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 c=oT(i,s,this.dir);c.lastModified=a;let p=cn.relative(this.dir,s),m=nT(c,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(c.name);if(u){let f=`duplicate skill name "${c.name}" \u2014 already defined in "${u}"`;t.push({file:p,errors:[f]}),this.onValidationError==="warn"&&console.warn(`[skills] Skipping "${p}": ${f}`);continue}n.set(c.name,p),o.push(c)}if(t.length>0&&this.onValidationError==="fail"){let s=t.map(i=>` ${i.file}:
609
+ ${i.errors.join(`
610
+ `)}`).join(`
611
+ `);throw new Error(`Skills validation failed \u2014 fix the following files before starting:
612
+ ${s}`)}for(let s of o)this.skills.set(s.name,s),this.index.addDocument(s.name,this.buildIndexContent(s));this.loaded=!0}async ensureLoaded(){if(this._buildPromise)return this._buildPromise;let e=await this.findSkillFiles(this.dir);if(this._buildPromise)return this._buildPromise;if(await this.needsRebuild(e))return this._buildPromise?this._buildPromise:(this._buildPromise=this.buildIndex(e).finally(()=>{this._buildPromise=null}),this._buildPromise)}async search(e,t,o){await this.ensureLoaded();let n=this.index.search(e,t),s=[];for(let i of n){if(i.score<o)continue;let a=this.skills.get(i.id);a&&s.push({skill:a,score:i.score})}return s}async get(e){return await this.ensureLoaded(),this.skills.get(e)}async list(e){await this.ensureLoaded();let t=Array.from(this.skills.values());return e?.tag?t.filter(o=>o.tags.includes(e.tag)):t}};function rT(r){let e=r?.dir??".toolpack/skills",t=r?.maxSkills??3,o=r?.minScore??.3,n=r?.onValidationError??"fail",s=new Ts({dir:e,onValidationError:n});return Object.assign(async(i,a)=>{let c=i.messages??[],p=-1;for(let f=c.length-1;f>=0;f--)if(c[f].role==="user"){p=f;break}let m=p>=0?c[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>
613
+ ${f.map(v=>`--- Skill: ${v.skill.title} ---
614
+ ${v.skill.instructions.trim()}
615
+ ---`).join(`
616
+
617
+ `)}
618
+ </skill-instructions>`,w=c.map((v,C)=>C===p&&typeof v.content=="string"?{...v,content:`${y}
619
+
620
+ ${v.content}`}:v);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});