toolpack-sdk 2.7.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var Bw=Object.defineProperty;var h=(r,e)=>()=>(r&&(e=r(r=0)),e);var ne=(r,e)=>{for(var t in e)Bw(r,t,{get:e[t],enumerable:!0})};import zw from"path";import{fileURLToPath as Hw}from"url";var Kw,Jw,u,c=h(()=>{"use strict";Kw=()=>Hw(import.meta.url),Jw=()=>zw.dirname(Kw()),u=Jw()});function Pk(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 _k(r,e){return r instanceof Vr?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof Kr?{shouldRetry:!1,shouldFallback:!0,action:r.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${r.strategy}`}:r instanceof Jr?{shouldRetry:!1,shouldFallback:!0,action:"fail",message:"Insufficient context after recovery attempts"}:{shouldRetry:!1,shouldFallback:!1,action:"none",message:"Unknown context window error"}}var j,he,re,O,F,Xe,fa,ga,Kr,Jr,Vr,ha,ya,se=h(()=>{"use strict";c();j=class extends Error{constructor(t,o,n,s){super(t);this.code=o;this.statusCode=n;this.cause=s;this.name="SDKError"}code;statusCode;cause},he=class extends j{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},re=class extends j{constructor(t,o,n){super(t,"RATE_LIMIT_ERROR",429,n);this.retryAfter=o;this.name="RateLimitError"}retryAfter},O=class extends j{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},F=class extends j{constructor(e,t="PROVIDER_ERROR",o=500,n){super(e,t,o,n),this.name="ProviderError"}},Xe=class extends j{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},fa=class extends j{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},ga=class extends j{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},Kr=class extends j{constructor(t,o,n,s,i,a){super(t,"CONTEXT_WINDOW_EXCEEDED",400,a);this.conversationId=o;this.currentTokens=n;this.contextWindowLimit=s;this.strategy=i;this.name="ContextWindowExceededError"}conversationId;currentTokens;contextWindowLimit;strategy;getOverageTokens(){return Math.max(0,this.currentTokens-this.contextWindowLimit)}getUsagePercentage(){return Math.round(this.currentTokens/this.contextWindowLimit*100)}getDetailedReport(){return`
1
+ var Iw=Object.defineProperty;var h=(r,e)=>()=>(r&&(e=r(r=0)),e);var oe=(r,e)=>{for(var t in e)Iw(r,t,{get:e[t],enumerable:!0})};import Lw from"path";import{fileURLToPath as jw}from"url";var Fw,qw,u,l=h(()=>{"use strict";Fw=()=>jw(import.meta.url),qw=()=>Lw.dirname(Fw()),u=qw()});function yk(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 bk(r,e){return r instanceof Ur?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof qr?{shouldRetry:!1,shouldFallback:!0,action:r.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${r.strategy}`}:r instanceof Wr?{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,ge,ie,M,I,Qe,la,ca,qr,Wr,Ur,pa,ma,ae=h(()=>{"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},ge=class extends N{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},ie=class extends N{constructor(t,o,n){super(t,"RATE_LIMIT_ERROR",429,n);this.retryAfter=o;this.name="RateLimitError"}retryAfter},M=class extends N{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},I=class extends N{constructor(e,t="PROVIDER_ERROR",o=500,n){super(e,t,o,n),this.name="ProviderError"}},Qe=class extends N{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},la=class extends N{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},ca=class extends N{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},qr=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()}},Jr=class extends j{constructor(t,o,n,s,i,a){super(t,"INSUFFICIENT_CONTEXT",400,a);this.conversationId=o;this.requiredTokens=n;this.availableTokens=s;this.minimumRequiredTokens=i;this.name="InsufficientContextError"}conversationId;requiredTokens;availableTokens;minimumRequiredTokens;getDeficit(){return Math.max(0,this.requiredTokens-this.availableTokens)}isRecoverable(){return this.availableTokens>=this.minimumRequiredTokens*.5}getDetailedReport(){return`
12
+ `.trim()}},Wr=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()}},Vr=class extends j{constructor(t,o,n,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=n;this.failureReason=s;this.summaryAttempt=i;this.name="SummarizationError"}conversationId;messageCount;failureReason;summaryAttempt;isRetryable(){return this.failureReason==="provider_error"||this.failureReason==="insufficient_tokens"}getSuggestedRecovery(){switch(this.failureReason){case"provider_error":return"Retry the summarization request or switch to a different summarizer model";case"invalid_response":return"Review the summarizer prompt or use a different model";case"insufficient_tokens":return"Reduce the number of messages to summarize or increase the summary token budget";case"invalid_quality":return"Adjust summarization parameters or use a more capable model";default:return"Manual intervention required"}}getDetailedReport(){let t=`
23
+ `.trim()}},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()}},ha=class extends j{constructor(t,o,n,s,i){super(t,"CONTEXT_WINDOW_CONFIG_ERROR",400,i);this.configField=o;this.providedValue=n;this.constraint=s;this.name="ContextWindowConfigError"}configField;providedValue;constraint;getDetailedReport(){return`
35
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}},pa=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,58 +40,58 @@ Provided Value: ${JSON.stringify(this.providedValue)}
40
40
  Constraint: ${this.constraint}
41
41
 
42
42
  Message: ${this.message}
43
- `.trim()}},ya=class extends j{constructor(t,o,n){super(t,"CONVERSATION_NOT_FOUND",404,n);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var gt,Ut,nT,_a=h(()=>{"use strict";c();gt={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},Ut=class{documents=[];avgDocLength=0;idf=new Map;totalDocs=0;docFrequencies=new Map;k1=1.2;b=.75;index(e){this.documents=[],this.docFrequencies.clear(),this.idf.clear();for(let t of e){let o=this.createDocument(t);this.documents.push(o);let n=new Set(o.tokens);for(let s of n)this.docFrequencies.set(s,(this.docFrequencies.get(s)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let o=t?.limit??5,n=t?.category,s=t?.minScore??0,i=this.tokenize(e.toLowerCase());if(i.length===0)return[];let a=[];for(let l of this.documents){if(n&&l.tool.category!==n)continue;let p=this.computeBM25Score(i,l);p>s&&a.push({toolName:l.toolName,score:p,tool:l.tool})}return a.sort((l,p)=>p.score-l.score).slice(0,o).map(({toolName:l,score:p,tool:m})=>({toolName:l,score:p,tool:this.toSchema(m)}))}getIndexedCount(){return this.documents.length}isIndexed(e){return this.documents.some(t=>t.toolName===e)}createDocument(e){let t=[];for(let i=0;i<gt.name;i++)t.push(e.name);for(let i=0;i<gt.displayName;i++)t.push(e.displayName);for(let i=0;i<gt.description;i++)t.push(e.description);for(let i=0;i<gt.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<gt.parameterNames;l++)t.push(i);if(a.description)for(let l=0;l<gt.parameterDescriptions;l++)t.push(a.description)}let o=t.join(" ").toLowerCase(),n=this.tokenize(o),s=this.computeTermFrequencies(n);return{toolName:e.name,tool:e,text:o,tokens:n,length:n.length,termFrequencies:s}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!nT.has(t))}computeTermFrequencies(e){let t=new Map;for(let o of e)t.set(o,(t.get(o)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let o=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,o)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,o)=>t+o.length,0)/this.documents.length}computeBM25Score(e,t){let o=0;for(let n of e){let s=t.termFrequencies.get(n)||0;if(s===0)continue;let i=this.idf.get(n)||0,a=t.length,l=s*(this.k1+1),p=s+this.k1*(1-this.b+this.b*(a/this.avgDocLength));o+=i*(l/p)}return o}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},nT=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there"])});var ht,Ra=h(()=>{"use strict";c();ht=class r{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let o of t)this.discoveredTools.add(o);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new r;for(let o of e)if(o.role==="tool"){let n=o;if(typeof n.content=="string")try{let s=JSON.parse(n.content);if(s.query&&s.tools&&Array.isArray(s.tools)){let i=s.tools.map(a=>typeof a=="string"?a:a.name).filter(Boolean);i.length>0&&t.recordDiscovery(s.query,i)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}}});function Ze(){return{name:yt.name,displayName:yt.displayName,description:yt.description,parameters:yt.parameters,category:yt.category}}function bt(r){return r===Ye}var Ye,yt,$a=h(()=>{"use strict";c();Ye="tool.search",yt={name:Ye,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
43
+ `.trim()}},ma=class extends N{constructor(t,o,n){super(t,"CONVERSATION_NOT_FOUND",404,n);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var gt,qt,Vw,xa=h(()=>{"use strict";l();gt={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},qt=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<gt.name;i++)t.push(e.name);for(let i=0;i<gt.displayName;i++)t.push(e.displayName);for(let i=0;i<gt.description;i++)t.push(e.description);for(let i=0;i<gt.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<gt.parameterNames;c++)t.push(i);if(a.description)for(let c=0;c<gt.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=>!Vw.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}}},Vw=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there"])});var ht,va=h(()=>{"use strict";l();ht=class r{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let o of t)this.discoveredTools.add(o);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new r;for(let o of e)if(o.role==="tool"){let n=o;if(typeof n.content=="string")try{let s=JSON.parse(n.content);if(s.query&&s.tools&&Array.isArray(s.tools)){let i=s.tools.map(a=>typeof a=="string"?a:a.name).filter(Boolean);i.length>0&&t.recordDiscovery(s.query,i)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}}});function Ye(){return{name:yt.name,displayName:yt.displayName,description:yt.description,parameters:yt.parameters,category:yt.category}}function bt(r){return r===Xe}var Xe,yt,Ca=h(()=>{"use strict";l();Xe="tool.search",yt={name:Xe,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
44
44
  Use this to discover tools before using them.
45
45
  Examples: "file operations", "web scraping", "run command", "http request"
46
46
 
47
47
  Returns a list of matching tools with their names, descriptions, and parameters.
48
- After discovering tools, you can call them directly by name.`,parameters:{type:"object",properties:{query:{type:"string",description:'Natural language search query (e.g., "read files", "web scraping", "execute shell commands")'},category:{type:"string",description:"Optional: filter by category",enum:["filesystem","network","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}}});function ts(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=rT[o]||o;t.push(`- **${o}** (${s} tools): ${i}`)}return t.push(""),t.push("Use `tool.search` to discover specific tools when needed."),t.push('Example: tool.search({ query: "read file" }) to find file reading tools.'),t.join(`
49
- `)}var rT,Ea=h(()=>{"use strict";c();rT={filesystem:"File operations (read, write, delete, list, search files)",network:"HTTP requests and web scraping (GET, POST, fetch pages, extract data)",execution:"Run shell commands and manage processes",system:"System information, environment variables, disk usage",meta:"Tool discovery and management"}});var Gt=h(()=>{"use strict";c();_a();Ra();$a();Ea()});var sT,ce,zt=h(()=>{"use strict";c();sT={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},ce={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:sT}});import{appendFileSync as Aa,mkdirSync as iT}from"fs";import{dirname as aT,isAbsolute as lT,join as cT,resolve as pT}from"path";function Ma(r){if(!r)return;let e=r.toLowerCase();if(e in os)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function Na(r){if(r?.enabled!==void 0&&(Tt=r.enabled),r?.filePath&&(Ce=r.filePath),r?.level&&(Ht=Ma(r.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(Tt=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(Ce=process.env.TOOLPACK_SDK_LOG_FILE,Tt=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(Ht=Ma(process.env.TOOLPACK_SDK_LOG_LEVEL)||Ht),process.env.TOOLPACK_SDK_LOG_CONSOLE!==void 0&&(ns=process.env.TOOLPACK_SDK_LOG_CONSOLE==="true"),r?.console!==void 0&&process.env.TOOLPACK_SDK_LOG_CONSOLE===void 0&&(ns=r.console),Tt)try{Ce=lT(Ce)?Ce:pT(process.cwd(),Ce),iT(aT(Ce),{recursive:!0}),Aa(Ce,`[${new Date().toISOString()}] [INFO] [Logger] initialized level=${Ht} file=${Ce}
50
- `)}catch(e){console.warn(`[Toolpack Warning] Failed to initialize log file "${Ce}": ${e.message}`),Tt=!1}}function tt(r){return Tt?os[r]<=os[Ht]:!1}function Kt(r,e){if(!tt(r))return;let o=`[${new Date().toISOString()}] [${r.toUpperCase()}] ${Oa(e)}`;Aa(Ce,o+`
51
- `),ns&&(r==="error"?console.error:r==="warn"?console.warn:console.log)(o)}function pe(r){Kt("error",r)}function L(r){Kt("warn",r)}function P(r){Kt("info",r)}function y(r){Kt("debug",r)}function Le(r){Kt("trace",r)}function Oa(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 A(r,e=200){try{let t=typeof r=="string"?r:JSON.stringify(r),o=Oa(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function Z(r,e,t){tt("debug")&&(y(`[${e}][${r}] Messages (${t.length}):`),t.forEach((o,n)=>{y(`[${e}][${r}] #${n} role=${o?.role} content=${A(o?.content,300)}`)}))}var os,Tt,Ht,Ce,ns,S=h(()=>{"use strict";c();os={error:0,warn:1,info:2,debug:3,trace:4},Tt=!1,Ht="info",Ce=cT(process.cwd(),"toolpack-sdk.log"),ns=!1});var Jt={};ne(Jt,{fetchUrlAsBase64:()=>Ka,getMimeType:()=>Ga,isDataUri:()=>Ba,normalizeImagePart:()=>wT,parseDataUri:()=>za,readFileAsBase64:()=>Ha,toDataUri:()=>bT});import*as Wa from"fs/promises";import*as Ua from"path";function Ga(r){let e=Ua.extname(r).toLowerCase();return yT[e]||"application/octet-stream"}function Ba(r){return r.startsWith("data:")}function za(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function bT(r,e){return`data:${e};base64,${r}`}async function Ha(r){try{return{data:(await Wa.readFile(r)).toString("base64"),mimeType:Ga(r)}}catch(e){throw new O(`Failed to read image file: ${r}`,e)}}async function Ka(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 wT(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await Ha(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(Ba(e)){let t=za(e);if(!t)throw new O(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Ka(e)}throw new O(`Unknown ImagePart type: ${r.type}`)}var yT,vt=h(()=>{"use strict";c();se();yT={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var nl,rl,sl,il,al,ll=h(()=>{"use strict";c();nl="fs.read_file",rl="Read File",sl="Read the contents of a file at the given path. Returns the file content as a string.",il="filesystem",al={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});import*as kt from"fs";async function DT(r){let e=r.path,t=r.encoding||"utf-8";if(y(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!kt.existsSync(e))throw new Error(`File not found: ${e}`);if(kt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return kt.readFileSync(e,t)}var Yt,ps=h(()=>{"use strict";c();ll();S();Yt={name:nl,displayName:rl,description:sl,parameters:al,category:il,execute:DT}});var cl,pl,ml,dl,ul,fl=h(()=>{"use strict";c();cl="fs.write_file",pl="Write File",ml="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.",dl="filesystem",ul={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as St from"fs";import*as gl from"path";async function MT(r){let e=r.path,t=r.content,o=r.encoding||"utf-8";if(y(`[fs.write-file] execute path="${e}" encoding=${o} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let n=gl.dirname(e);return St.existsSync(n)||St.mkdirSync(n,{recursive:!0}),St.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var Zt,ms=h(()=>{"use strict";c();fl();S();Zt={name:cl,displayName:pl,description:ml,parameters:ul,category:dl,execute:MT,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var hl,yl,bl,wl,Tl,xl=h(()=>{"use strict";c();hl="fs.append_file",yl="Append File",bl="Append content to the end of a file. Creates the file if it does not exist.",wl="filesystem",Tl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as Pt from"fs";import*as vl from"path";async function AT(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=vl.dirname(e);return Pt.existsSync(n)||Pt.mkdirSync(n,{recursive:!0}),Pt.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var eo,ds=h(()=>{"use strict";c();xl();eo={name:hl,displayName:yl,description:bl,parameters:Tl,category:wl,execute:AT,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var Cl,kl,Sl,Pl,_l,Rl=h(()=>{"use strict";c();Cl="fs.delete_file",kl="Delete File",Sl="Remove/delete a file from the filesystem. Does not delete directories.",Pl="filesystem",_l={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as _t from"fs";async function NT(r){let e=r.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!_t.existsSync(e))throw new Error(`File not found: ${e}`);if(_t.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return _t.unlinkSync(e),`File deleted successfully: ${e}`}var to,us=h(()=>{"use strict";c();Rl();S();to={name:Cl,displayName:kl,description:Sl,parameters:_l,category:Pl,execute:NT,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var $l,El,Dl,Ml,Al,Nl=h(()=>{"use strict";c();$l="fs.exists",El="Exists",Dl="Check if a file or directory exists at the given path. Returns true or false.",Ml="filesystem",Al={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as Ol from"fs";async function OT(r){let e=r.path;if(!e)throw new Error("path is required");let t=Ol.existsSync(e);return JSON.stringify({exists:t,path:e})}var oo,fs=h(()=>{"use strict";c();Nl();oo={name:$l,displayName:El,description:Dl,parameters:Al,category:Ml,execute:OT}});var Il,jl,Ll,Fl,ql,Wl=h(()=>{"use strict";c();Il="fs.stat",jl="Stat",Ll="Get file or directory information including size, type, and modification date.",Fl="filesystem",ql={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as jn from"fs";async function IT(r){let e=r.path;if(!e)throw new Error("path is required");if(!jn.existsSync(e))throw new Error(`Path not found: ${e}`);let t=jn.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 no,gs=h(()=>{"use strict";c();Wl();no={name:Il,displayName:jl,description:Ll,parameters:ql,category:Fl,execute:IT}});var Ul,Gl,Bl,zl,Hl,Kl=h(()=>{"use strict";c();Ul="fs.list_dir",Gl="List Directory",Bl="List files and directories at the given path. Optionally recurse into subdirectories.",zl="filesystem",Hl={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});import*as rt from"fs";import*as Jl from"path";function Vl(r,e,t,o=""){let n=rt.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=Jl.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&Vl(i,!0,t,a);else if(s.isFile()){let l=rt.statSync(i);t.push({name:a,type:"file",size:l.size})}}}async function jT(r){let e=r.path,t=r.recursive===!0;if(!e)throw new Error("path is required");if(!rt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!rt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[];return Vl(e,t,n),JSON.stringify(n,null,2)}var ro,hs=h(()=>{"use strict";c();Kl();ro={name:Ul,displayName:Gl,description:Bl,parameters:Hl,category:zl,execute:jT}});var Ql,Xl,Yl,Zl,ec,tc=h(()=>{"use strict";c();Ql="fs.create_dir",Xl="Create Directory",Yl="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Zl="filesystem",ec={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});import*as Rt from"fs";async function LT(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(Rt.existsSync(e)){if(Rt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Rt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var so,ys=h(()=>{"use strict";c();tc();so={name:Ql,displayName:Xl,description:Yl,parameters:ec,category:Zl,execute:LT}});var oc,nc,rc,sc,ic,ac=h(()=>{"use strict";c();oc="fs.move",nc="Move",rc="Move or rename a file or directory from one path to another.",sc="filesystem",ic={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as st from"fs";import*as lc from"path";async function FT(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(!st.existsSync(e))throw new Error(`Source not found: ${e}`);let o=lc.dirname(t);return st.existsSync(o)||st.mkdirSync(o,{recursive:!0}),st.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var io,bs=h(()=>{"use strict";c();ac();io={name:oc,displayName:nc,description:rc,parameters:ic,category:sc,execute:FT,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var cc,pc,mc,dc,uc,fc=h(()=>{"use strict";c();cc="fs.copy",pc="Copy",mc="Copy a file or directory from one path to another. Recursively copies directories.",dc="filesystem",uc={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as me from"fs";import*as ao from"path";function gc(r,e){if(me.statSync(r).isDirectory()){me.existsSync(e)||me.mkdirSync(e,{recursive:!0});let o=me.readdirSync(r);for(let n of o)gc(ao.join(r,n),ao.join(e,n))}else me.copyFileSync(r,e)}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(!me.existsSync(e))throw new Error(`Source not found: ${e}`);let o=ao.dirname(t);return me.existsSync(o)||me.mkdirSync(o,{recursive:!0}),gc(e,t),`Copied ${me.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var lo,ws=h(()=>{"use strict";c();fc();lo={name:cc,displayName:pc,description:mc,parameters:uc,category:dc,execute:qT,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var hc,yc,bc,wc,Tc,xc=h(()=>{"use strict";c();hc="fs.read_file_range",yc="Read File Range",bc="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",wc="filesystem",Tc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});import*as $t from"fs";async function WT(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(!$t.existsSync(e))throw new Error(`File not found: ${e}`);if($t.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=$t.readFileSync(e,"utf-8").split(`
52
- `),a=i.length,l=Math.min(t,a),p=Math.min(o,a),d=i.slice(l-1,p).map((g,b)=>`${l+b}: ${g}`).join(`
53
- `);return`Lines ${l}-${p} of ${a} total:
54
- ${d}`}var co,Ts=h(()=>{"use strict";c();xc();co={name:hc,displayName:yc,description:bc,parameters:Tc,category:wc,execute:WT}});var vc,Cc,kc,Sc,Pc,_c=h(()=>{"use strict";c();vc="fs.search",Cc="Search",kc="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Sc="filesystem",Pc={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});import*as qe from"fs";import*as Rc from"path";function UT(r,e,t,o){try{let s=qe.readFileSync(r,"utf-8").split(`
55
- `);for(let i=0;i<s.length&&t.length<o;i++){let a=s[i];(typeof e=="string"?a.includes(e):e.test(a))&&t.push({file:r,line:i+1,content:a.trim()})}}catch{}}function $c(r,e,t,o,n){let s=qe.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=Rc.join(r,i.name);i.isDirectory()&&t?$c(a,e,!0,o,n):i.isFile()&&UT(a,e,o,n)}}async function GT(r){let e=r.path,t=r.query,o=r.recursive!==!1,n=r.max_results||50,s=!!r.regex,i=!!r.case_sensitive;if(y(`[fs.search] execute path="${e}" query="${t}" recursive=${o} regex=${s} caseSensitive=${i}`),!e)throw new Error("path is required");if(!t)throw new Error("query is required");let a=t;if(s||!i){let d=t;s||(d=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let g=i?"":"i";a=new RegExp(d,g)}if(!qe.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!qe.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if($c(e,a,o,p,n),p.length===0)return`No matches found for "${t}" in ${e}`;let m=p.length>=n?`
56
- (results capped at ${n})`:"";return JSON.stringify(p,null,2)+m}var po,xs=h(()=>{"use strict";c();_c();S();po={name:vc,displayName:Cc,description:kc,parameters:Pc,category:Sc,execute:GT}});var Ec,Dc,Mc,Ac,Nc,Oc=h(()=>{"use strict";c();Ec="fs.replace_in_file",Dc="Replace In File",Mc="Find and replace text in a file. Returns the number of replacements made.",Ac="filesystem",Nc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});import*as We from"fs";async function BT(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(!We.existsSync(e))throw new Error(`File not found: ${e}`);if(We.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let s=We.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 We.writeFileSync(e,l,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var mo,vs=h(()=>{"use strict";c();Oc();mo={name:Ec,displayName:Dc,description:Mc,parameters:Nc,category:Ac,execute:BT,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 Ic,jc,Lc,Fc,qc,Wc=h(()=>{"use strict";c();Ic="fs.tree",jc="Tree",Lc="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Fc="filesystem",qc={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});import*as Et from"fs";import*as Ln from"path";function Uc(r,e,t,o,n){if(t>o)return;let i=Et.readdirSync(r,{withFileTypes:!0}).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name));for(let a=0;a<i.length;a++){let l=i[a],p=a===i.length-1,m=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=p?" ":"\u2502 ";l.isDirectory()?(n.push(`${e}${m}${l.name}/`),Uc(Ln.join(r,l.name),e+d,t+1,o,n)):n.push(`${e}${m}${l.name}`)}}async function zT(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!Et.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Et.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${Ln.basename(e)}/`];return Uc(e,"",1,t,s),s.join(`
57
- `)}var uo,Cs=h(()=>{"use strict";c();Wc();uo={name:Ic,displayName:jc,description:Lc,parameters:qc,category:Fc,execute:zT}});var Gc,Bc,zc,Hc,Kc,Jc=h(()=>{"use strict";c();Gc="fs.glob",Bc="Glob Pattern Match",zc='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',Hc="filesystem",Kc={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});import HT from"fast-glob";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 l=await HT(a,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:n,onlyDirectories:s,absolute:i,dot:!0});return JSON.stringify({pattern:e,files:l,count:l.length},null,2)}catch(l){throw new Error(`Failed to glob pattern "${e}": ${l.message}`)}}var fo,ks=h(()=>{"use strict";c();Jc();fo={name:Gc,displayName:Bc,description:zc,parameters:Kc,category:Hc,execute:KT}});var Vc,Qc,Xc,Yc,Zc,ep=h(()=>{"use strict";c();Vc="fs.delete_dir",Qc="Delete Directory",Xc="Delete a directory and all its contents recursively",Yc="filesystem",Zc={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});import{rm as JT}from"fs/promises";import{existsSync as VT,statSync as QT}from"fs";async function XT(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!VT(e))throw new Error(`Directory does not exist: ${e}`);if(!QT(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await JT(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var go,Ss=h(()=>{"use strict";c();ep();go={name:Vc,displayName:Qc,description:Xc,parameters:Zc,category:Yc,execute:XT,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var tp,op,np,rp,sp,ip=h(()=>{"use strict";c();tp="fs.batch_read",op="Batch Read Files",np="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",rp="filesystem",sp={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});import{readFile as YT}from"fs/promises";async function ZT(r){let e=r.paths,t=r.encoding||"utf-8",o=r.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let n=[],s=0,i=0;for(let a of e)try{let l=await YT(a,t);n.push({path:a,content:l,success:!0}),s++}catch(l){let p=l.message;if(n.push({path:a,error:p,success:!1}),i++,!o)throw new Error(`Failed to read file "${a}": ${p}`)}return JSON.stringify({total:e.length,success:s,failed:i,results:n},null,2)}var ho,Ps=h(()=>{"use strict";c();ip();ho={name:tp,displayName:op,description:np,parameters:sp,category:rp,execute:ZT}});var ap,lp,cp,pp,mp,dp=h(()=>{"use strict";c();ap="fs.batch_write",lp="Batch Write Files",cp="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",pp="filesystem",mp={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});import{writeFile as up,mkdir as ex,readFile as tx,unlink as ox}from"fs/promises";import{dirname as nx,resolve as rx}from"path";import{existsSync as fp}from"fs";async function sx(r){let e=r.files,t=r.encoding||"utf-8",o=r.atomic!==!1,n=r.createDirs!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("files array is required and must not be empty");for(let a of e)if(!a.path||a.content===void 0)throw new Error("Each file must have path and content properties");let s=[],i=[];try{for(let a of e){let l=rx(a.path);if(o){let p=fp(l),m={path:l,existed:p};p&&(m.originalContent=await tx(l,t)),s.push(m)}if(n){let p=nx(l);await ex(p,{recursive:!0})}await up(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 up(l.path,l.originalContent,t):!l.existed&&fp(l.path)&&await ox(l.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var yo,_s=h(()=>{"use strict";c();dp();yo={name:ap,displayName:lp,description:cp,parameters:mp,category:pp,execute:sx,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var hp={};ne(hp,{fsAppendFileTool:()=>eo,fsBatchReadTool:()=>ho,fsBatchWriteTool:()=>yo,fsCopyTool:()=>lo,fsCreateDirTool:()=>so,fsDeleteDirTool:()=>go,fsDeleteFileTool:()=>to,fsExistsTool:()=>oo,fsGlobTool:()=>fo,fsListDirTool:()=>ro,fsMoveTool:()=>io,fsReadFileRangeTool:()=>co,fsReadFileTool:()=>Yt,fsReplaceInFileTool:()=>mo,fsSearchTool:()=>po,fsStatTool:()=>no,fsToolsProject:()=>gp,fsTreeTool:()=>uo,fsWriteFileTool:()=>Zt});var gp,Rs=h(()=>{"use strict";c();ps();ms();ds();us();fs();gs();hs();ys();bs();ws();Ts();xs();vs();Cs();ks();Ss();Ps();_s();ps();ms();ds();us();fs();gs();hs();ys();bs();ws();Ts();xs();vs();Cs();ks();Ss();Ps();_s();gp={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:[Yt,Zt,eo,to,oo,no,ro,so,io,lo,co,po,mo,uo,fo,go,ho,yo],dependencies:{"fast-glob":"^3.3.2"}}});var yp,bp,wp,Tp,xp,vp=h(()=>{"use strict";c();yp="exec.run",bp="Run",wp="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Tp="execution",xp={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});import{execSync as ix}from"child_process";async function ax(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return ix(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"}):
48
+ After discovering tools, you can call them directly by name.`,parameters:{type:"object",properties:{query:{type:"string",description:'Natural language search query (e.g., "read files", "web scraping", "execute shell commands")'},category:{type:"string",description:"Optional: filter by category",enum:["filesystem","network","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}}});function Jr(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=Qw[o]||o;t.push(`- **${o}** (${s} tools): ${i}`)}return t.push(""),t.push("Use `tool.search` to discover specific tools when needed."),t.push('Example: tool.search({ query: "read file" }) to find file reading tools.'),t.join(`
49
+ `)}var Qw,ka=h(()=>{"use strict";l();Qw={filesystem:"File operations (read, write, delete, list, search files)",network:"HTTP requests and web scraping (GET, POST, fetch pages, extract data)",execution:"Run shell commands and manage processes",system:"System information, environment variables, disk usage",meta:"Tool discovery and management"}});var Wt=h(()=>{"use strict";l();xa();va();Ca();ka()});import{appendFileSync as Pa,mkdirSync as Yw}from"fs";import{dirname as Zw,isAbsolute as eT,join as tT,resolve as oT}from"path";function _a(r){if(!r)return;let e=r.toLowerCase();if(e in Vr)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function Ra(r){et.init(r)}function Tt(r){return et.shouldLog(r)}function me(r){et.error(r)}function O(r){et.warn(r)}function P(r){et.info(r)}function y(r){et.debug(r)}function Fe(r){et.trace(r)}function $a(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 D(r,e=200){try{let t=typeof r=="string"?r:JSON.stringify(r),o=$a(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function Z(r,e,t){Tt("debug")&&(y(`[${e}][${r}] Messages (${t.length}):`),t.forEach((o,n)=>{y(`[${e}][${r}] #${n} role=${o?.role} content=${D(o?.content,300)}`)}))}var Vr,Qr,et,S=h(()=>{"use strict";l();Vr={error:0,warn:1,info:2,debug:3,trace:4},Qr=class{_enabled=!1;_level="info";_logFile=tT(process.cwd(),"toolpack-sdk.log");_console=!1;init(e){if(e?.enabled!==void 0&&(this._enabled=e.enabled),e?.filePath&&(this._logFile=e.filePath),e?.level&&(this._level=_a(e.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(this._enabled=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(this._logFile=process.env.TOOLPACK_SDK_LOG_FILE,this._enabled=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(this._level=_a(process.env.TOOLPACK_SDK_LOG_LEVEL)||this._level),process.env.TOOLPACK_SDK_LOG_CONSOLE!==void 0?this._console=process.env.TOOLPACK_SDK_LOG_CONSOLE==="true":e?.console!==void 0&&(this._console=e.console),this._enabled)try{this._logFile=eT(this._logFile)?this._logFile:oT(process.cwd(),this._logFile),Yw(Zw(this._logFile),{recursive:!0}),Pa(this._logFile,`[${new Date().toISOString()}] [INFO] [Logger] initialized level=${this._level} file=${this._logFile}
50
+ `)}catch(t){console.warn(`[Toolpack Warning] Failed to initialize log file "${this._logFile}": ${t.message}`),this._enabled=!1}}shouldLog(e){return this._enabled&&Vr[e]<=Vr[this._level]}getLevel(){return this._level}write(e,t){if(!this.shouldLog(e))return;let o=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${$a(t)}`;Pa(this._logFile,o+`
51
+ `),this._console&&(e==="error"?console.error:e==="warn"?console.warn:console.log)(o)}error(e){this.write("error",e)}warn(e){this.write("warn",e)}info(e){this.write("info",e)}debug(e){this.write("debug",e)}trace(e){this.write("trace",e)}},et=new Qr});var Gt={};oe(Gt,{fetchUrlAsBase64:()=>Fa,getMimeType:()=>Oa,isDataUri:()=>Ia,normalizeImagePart:()=>dT,parseDataUri:()=>La,readFileAsBase64:()=>ja,toDataUri:()=>mT});import*as Aa from"fs/promises";import*as Na from"path";function Oa(r){let e=Na.extname(r).toLowerCase();return pT[e]||"application/octet-stream"}function Ia(r){return r.startsWith("data:")}function La(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function mT(r,e){return`data:${e};base64,${r}`}async function ja(r){try{return{data:(await Aa.readFile(r)).toString("base64"),mimeType:Oa(r)}}catch(e){throw new M(`Failed to read image file: ${r}`,e)}}async function Fa(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 I(`Failed to download image from URL: ${r}`,"FETCH_ERROR",500,e)}}async function dT(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await ja(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(Ia(e)){let t=La(e);if(!t)throw new M(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Fa(e)}throw new M(`Unknown ImagePart type: ${r.type}`)}var pT,vt=h(()=>{"use strict";l();ae();pT={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Ht,$e,nt=h(()=>{"use strict";l();Ht=class{processes=new Map;nextId=1;register(e,t,o){let n=`proc_${this.nextId++}`,s={id:n,command:e,cwd:t,process:o,startedAt:new Date().toISOString(),stdout:"",stderr:""};return o.stdout?.on("data",i=>{s.stdout+=i.toString(),s.stdout.length>1e6&&(s.stdout=s.stdout.slice(-5e5))}),o.stderr?.on("data",i=>{s.stderr+=i.toString(),s.stderr.length>1e6&&(s.stderr=s.stderr.slice(-5e5))}),this.processes.set(n,s),n}get(e){return this.processes.get(e)}kill(e){let t=this.processes.get(e);if(!t)return!1;let o=t.process.exitCode===null;return o&&t.process.kill("SIGTERM"),o}list(){return Array.from(this.processes.values()).map(e=>({id:e.id,command:e.command,cwd:e.cwd,startedAt:e.startedAt,alive:e.process.exitCode===null,pid:e.process.pid}))}remove(e){return this.processes.delete(e)}},$e=new Ht});import*as Va from"fs/promises";var Kt,Qa,os=h(()=>{"use strict";l();Kt=class{registry=new Map;mutexes=new Map;totalBytes=0;async acquireMutex(e){for(;this.mutexes.has(e);)await this.mutexes.get(e);let t,o=new Promise(n=>{t=n});return this.mutexes.set(e,o),()=>{this.mutexes.delete(e),t()}}async evictIfNeeded(e,t){let o=t-e;for(;this.totalBytes>o&&this.registry.size>0;){let n=null,s=null;for(let[i,a]of this.registry)(!n||a.lastAccessedAt<n.lastAccessedAt)&&(n=a,s=i);if(!s||!n)break;try{await Va.rm(n.cloneDir,{recursive:!0,force:!0}),this.totalBytes=Math.max(0,this.totalBytes-n.sizeBytes),this.registry.delete(s)}catch{break}}}},Qa=new Kt});import*as Ya from"crypto";async function B(r,e,t,o){return(t??ST).resolve(r,e,o)}function Xa(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=Ya.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var Jt,ST,be=h(()=>{"use strict";l();Jt=class{tokenCache=new Map;installationIdCache=new Map;async resolve(e,t,o){if(t)return t;let n=o?.githubPat??process.env.GITHUB_PAT;if(n)return n;let s=o?.githubAppId??process.env.GITHUB_APP_ID,i=(o?.githubAppPrivateKey??process.env.GITHUB_APP_PRIVATE_KEY)?.replace(/\\n/g,`
52
+ `);if(!s||!i)throw new Error("No GitHub token available. Set GITHUB_PAT, or GITHUB_APP_ID + GITHUB_APP_PRIVATE_KEY.");let a=await this._lookupInstallationId(s,i,e);return this._mintInstallationToken(s,i,a)}async _lookupInstallationId(e,t,o){if(!o)throw new Error("Cannot resolve GitHub App installation token without a repo name. Pass args.repo or set GITHUB_PAT.");let n=this.installationIdCache.get(o);if(n!==void 0)return n;let s=Xa(e,t),i=await fetch(`https://api.github.com/repos/${o}/installation`,{headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}});if(!i.ok){let c=await i.text();throw new Error(`Failed to look up installation for ${o} (${i.status}): ${c}`)}let a=await i.json();return this.installationIdCache.set(o,a.id),a.id}async _mintInstallationToken(e,t,o){let n=this.tokenCache.get(o);if(n&&n.expiresAt>Date.now()+6e4)return n.token;let s=Xa(e,t),i=await fetch(`https://api.github.com/app/installations/${o}/access_tokens`,{method:"POST",headers:{Authorization:`Bearer ${s}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}});if(!i.ok){let c=await i.text();throw new Error(`Failed to mint installation token (${i.status}): ${c}`)}let a=await i.json();return this.tokenCache.set(o,{token:a.token,expiresAt:new Date(a.expires_at).getTime()}),a.token}},ST=new Jt});var Za={};oe(Za,{ToolRuntimeContext:()=>ns});var ns,el=h(()=>{"use strict";l();nt();os();be();ns=class{processRegistry=new Ht;cloneState=new Kt;githubTokenStore=new Jt}});var tl,ol,nl,rl,sl,il=h(()=>{"use strict";l();tl="fs.read_file",ol="Read File",nl="Read the contents of a file at the given path. Returns the file content as a string.",rl="filesystem",sl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});import*as kt from"fs";async function PT(r){let e=r.path,t=r.encoding||"utf-8";if(y(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!kt.existsSync(e))throw new Error(`File not found: ${e}`);if(kt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return kt.readFileSync(e,t)}var Vt,rs=h(()=>{"use strict";l();il();S();Vt={name:tl,displayName:ol,description:nl,parameters:sl,category:rl,execute:PT}});var al,ll,cl,pl,ml,dl=h(()=>{"use strict";l();al="fs.write_file",ll="Write File",cl="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.",pl="filesystem",ml={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as St from"fs";import*as ul from"path";async function _T(r){let e=r.path,t=r.content,o=r.encoding||"utf-8";if(y(`[fs.write-file] execute path="${e}" encoding=${o} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let n=ul.dirname(e);return St.existsSync(n)||St.mkdirSync(n,{recursive:!0}),St.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var Qt,ss=h(()=>{"use strict";l();dl();S();Qt={name:al,displayName:ll,description:cl,parameters:ml,category:pl,execute:_T,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var fl,gl,hl,yl,bl,wl=h(()=>{"use strict";l();fl="fs.append_file",gl="Append File",hl="Append content to the end of a file. Creates the file if it does not exist.",yl="filesystem",bl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as Pt from"fs";import*as Tl from"path";async function RT(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=Tl.dirname(e);return Pt.existsSync(n)||Pt.mkdirSync(n,{recursive:!0}),Pt.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Xt,is=h(()=>{"use strict";l();wl();Xt={name:fl,displayName:gl,description:hl,parameters:bl,category:yl,execute:RT,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var xl,vl,Cl,kl,Sl,Pl=h(()=>{"use strict";l();xl="fs.delete_file",vl="Delete File",Cl="Remove/delete a file from the filesystem. Does not delete directories.",kl="filesystem",Sl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as _t from"fs";async function $T(r){let e=r.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!_t.existsSync(e))throw new Error(`File not found: ${e}`);if(_t.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return _t.unlinkSync(e),`File deleted successfully: ${e}`}var Yt,as=h(()=>{"use strict";l();Pl();S();Yt={name:xl,displayName:vl,description:Cl,parameters:Sl,category:kl,execute:$T,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var _l,Rl,$l,El,Dl,Ml=h(()=>{"use strict";l();_l="fs.exists",Rl="Exists",$l="Check if a file or directory exists at the given path. Returns true or false.",El="filesystem",Dl={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as Al from"fs";async function ET(r){let e=r.path;if(!e)throw new Error("path is required");let t=Al.existsSync(e);return JSON.stringify({exists:t,path:e})}var Zt,ls=h(()=>{"use strict";l();Ml();Zt={name:_l,displayName:Rl,description:$l,parameters:Dl,category:El,execute:ET}});var Nl,Ol,Il,Ll,jl,Fl=h(()=>{"use strict";l();Nl="fs.stat",Ol="Stat",Il="Get file or directory information including size, type, and modification date.",Ll="filesystem",jl={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as An from"fs";async function DT(r){let e=r.path;if(!e)throw new Error("path is required");if(!An.existsSync(e))throw new Error(`Path not found: ${e}`);let t=An.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 eo,cs=h(()=>{"use strict";l();Fl();eo={name:Nl,displayName:Ol,description:Il,parameters:jl,category:Ll,execute:DT}});var ql,Wl,Ul,Gl,Bl,zl=h(()=>{"use strict";l();ql="fs.list_dir",Wl="List Directory",Ul="List files and directories at the given path. Optionally recurse into subdirectories.",Gl="filesystem",Bl={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});import*as rt from"fs";import*as Hl from"path";function Kl(r,e,t,o=""){let n=rt.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=Hl.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&Kl(i,!0,t,a);else if(s.isFile()){let c=rt.statSync(i);t.push({name:a,type:"file",size:c.size})}}}async function MT(r){let e=r.path,t=r.recursive===!0;if(!e)throw new Error("path is required");if(!rt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!rt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[];return Kl(e,t,n),JSON.stringify(n,null,2)}var to,ps=h(()=>{"use strict";l();zl();to={name:ql,displayName:Wl,description:Ul,parameters:Bl,category:Gl,execute:MT}});var Jl,Vl,Ql,Xl,Yl,Zl=h(()=>{"use strict";l();Jl="fs.create_dir",Vl="Create Directory",Ql="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Xl="filesystem",Yl={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});import*as Rt from"fs";async function AT(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(Rt.existsSync(e)){if(Rt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Rt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var oo,ms=h(()=>{"use strict";l();Zl();oo={name:Jl,displayName:Vl,description:Ql,parameters:Yl,category:Xl,execute:AT}});var ec,tc,oc,nc,rc,sc=h(()=>{"use strict";l();ec="fs.move",tc="Move",oc="Move or rename a file or directory from one path to another.",nc="filesystem",rc={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as st from"fs";import*as ic from"path";async function NT(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(!st.existsSync(e))throw new Error(`Source not found: ${e}`);let o=ic.dirname(t);return st.existsSync(o)||st.mkdirSync(o,{recursive:!0}),st.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var no,ds=h(()=>{"use strict";l();sc();no={name:ec,displayName:tc,description:oc,parameters:rc,category:nc,execute:NT,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var ac,lc,cc,pc,mc,dc=h(()=>{"use strict";l();ac="fs.copy",lc="Copy",cc="Copy a file or directory from one path to another. Recursively copies directories.",pc="filesystem",mc={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as de from"fs";import*as ro from"path";function uc(r,e){if(de.statSync(r).isDirectory()){de.existsSync(e)||de.mkdirSync(e,{recursive:!0});let o=de.readdirSync(r);for(let n of o)uc(ro.join(r,n),ro.join(e,n))}else de.copyFileSync(r,e)}async function OT(r){let e=r.path,t=r.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!de.existsSync(e))throw new Error(`Source not found: ${e}`);let o=ro.dirname(t);return de.existsSync(o)||de.mkdirSync(o,{recursive:!0}),uc(e,t),`Copied ${de.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var so,us=h(()=>{"use strict";l();dc();so={name:ac,displayName:lc,description:cc,parameters:mc,category:pc,execute:OT,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var fc,gc,hc,yc,bc,wc=h(()=>{"use strict";l();fc="fs.read_file_range",gc="Read File Range",hc="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",yc="filesystem",bc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});import*as $t from"fs";async function IT(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(!$t.existsSync(e))throw new Error(`File not found: ${e}`);if($t.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=$t.readFileSync(e,"utf-8").split(`
53
+ `),a=i.length,c=Math.min(t,a),p=Math.min(o,a),d=i.slice(c-1,p).map((g,w)=>`${c+w}: ${g}`).join(`
54
+ `);return`Lines ${c}-${p} of ${a} total:
55
+ ${d}`}var io,fs=h(()=>{"use strict";l();wc();io={name:fc,displayName:gc,description:hc,parameters:bc,category:yc,execute:IT}});var Tc,xc,vc,Cc,kc,Sc=h(()=>{"use strict";l();Tc="fs.search",xc="Search",vc="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Cc="filesystem",kc={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});import*as We from"fs";import*as Pc from"path";function LT(r,e,t,o){try{let s=We.readFileSync(r,"utf-8").split(`
56
+ `);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 _c(r,e,t,o,n){let s=We.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=Pc.join(r,i.name);i.isDirectory()&&t?_c(a,e,!0,o,n):i.isFile()&&LT(a,e,o,n)}}async function jT(r){let e=r.path,t=r.query,o=r.recursive!==!1,n=r.max_results||50,s=!!r.regex,i=!!r.case_sensitive;if(y(`[fs.search] execute path="${e}" query="${t}" recursive=${o} regex=${s} caseSensitive=${i}`),!e)throw new Error("path is required");if(!t)throw new Error("query is required");let a=t;if(s||!i){let d=t;s||(d=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let g=i?"":"i";a=new RegExp(d,g)}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(_c(e,a,o,p,n),p.length===0)return`No matches found for "${t}" in ${e}`;let m=p.length>=n?`
57
+ (results capped at ${n})`:"";return JSON.stringify(p,null,2)+m}var ao,gs=h(()=>{"use strict";l();Sc();S();ao={name:Tc,displayName:xc,description:vc,parameters:kc,category:Cc,execute:jT}});var Rc,$c,Ec,Dc,Mc,Ac=h(()=>{"use strict";l();Rc="fs.replace_in_file",$c="Replace In File",Ec="Find and replace text in a file. Returns the number of replacements made.",Dc="filesystem",Mc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});import*as Ue from"fs";async function FT(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 lo,hs=h(()=>{"use strict";l();Ac();lo={name:Rc,displayName:$c,description:Ec,parameters:Mc,category:Dc,execute:FT,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 Nc,Oc,Ic,Lc,jc,Fc=h(()=>{"use strict";l();Nc="fs.tree",Oc="Tree",Ic="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Lc="filesystem",jc={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});import*as Et from"fs";import*as Nn from"path";function qc(r,e,t,o,n){if(t>o)return;let i=Et.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 ",d=p?" ":"\u2502 ";c.isDirectory()?(n.push(`${e}${m}${c.name}/`),qc(Nn.join(r,c.name),e+d,t+1,o,n)):n.push(`${e}${m}${c.name}`)}}async function qT(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!Et.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Et.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${Nn.basename(e)}/`];return qc(e,"",1,t,s),s.join(`
58
+ `)}var co,ys=h(()=>{"use strict";l();Fc();co={name:Nc,displayName:Oc,description:Ic,parameters:jc,category:Lc,execute:qT}});var Wc,Uc,Gc,Bc,zc,Hc=h(()=>{"use strict";l();Wc="fs.glob",Uc="Glob Pattern Match",Gc='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',Bc="filesystem",zc={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});import WT from"fast-glob";async function UT(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 WT(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 po,bs=h(()=>{"use strict";l();Hc();po={name:Wc,displayName:Uc,description:Gc,parameters:zc,category:Bc,execute:UT}});var Kc,Jc,Vc,Qc,Xc,Yc=h(()=>{"use strict";l();Kc="fs.delete_dir",Jc="Delete Directory",Vc="Delete a directory and all its contents recursively",Qc="filesystem",Xc={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});import{rm as GT}from"fs/promises";import{existsSync as BT,statSync as zT}from"fs";async function HT(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!BT(e))throw new Error(`Directory does not exist: ${e}`);if(!zT(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await GT(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var mo,ws=h(()=>{"use strict";l();Yc();mo={name:Kc,displayName:Jc,description:Vc,parameters:Xc,category:Qc,execute:HT,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var Zc,ep,tp,op,np,rp=h(()=>{"use strict";l();Zc="fs.batch_read",ep="Batch Read Files",tp="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",op="filesystem",np={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});import{readFile as KT}from"fs/promises";async function JT(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 KT(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 uo,Ts=h(()=>{"use strict";l();rp();uo={name:Zc,displayName:ep,description:tp,parameters:np,category:op,execute:JT}});var sp,ip,ap,lp,cp,pp=h(()=>{"use strict";l();sp="fs.batch_write",ip="Batch Write Files",ap="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",lp="filesystem",cp={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});import{writeFile as mp,mkdir as VT,readFile as QT,unlink as XT}from"fs/promises";import{dirname as YT,resolve as ZT}from"path";import{existsSync as dp}from"fs";async function ex(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=ZT(a.path);if(o){let p=dp(c),m={path:c,existed:p};p&&(m.originalContent=await QT(c,t)),s.push(m)}if(n){let p=YT(c);await VT(p,{recursive:!0})}await mp(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 mp(c.path,c.originalContent,t):!c.existed&&dp(c.path)&&await XT(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var fo,xs=h(()=>{"use strict";l();pp();fo={name:sp,displayName:ip,description:ap,parameters:cp,category:lp,execute:ex,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var fp={};oe(fp,{fsAppendFileTool:()=>Xt,fsBatchReadTool:()=>uo,fsBatchWriteTool:()=>fo,fsCopyTool:()=>so,fsCreateDirTool:()=>oo,fsDeleteDirTool:()=>mo,fsDeleteFileTool:()=>Yt,fsExistsTool:()=>Zt,fsGlobTool:()=>po,fsListDirTool:()=>to,fsMoveTool:()=>no,fsReadFileRangeTool:()=>io,fsReadFileTool:()=>Vt,fsReplaceInFileTool:()=>lo,fsSearchTool:()=>ao,fsStatTool:()=>eo,fsToolsProject:()=>up,fsTreeTool:()=>co,fsWriteFileTool:()=>Qt});var up,vs=h(()=>{"use strict";l();rs();ss();is();as();ls();cs();ps();ms();ds();us();fs();gs();hs();ys();bs();ws();Ts();xs();rs();ss();is();as();ls();cs();ps();ms();ds();us();fs();gs();hs();ys();bs();ws();Ts();xs();up={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:[Vt,Qt,Xt,Yt,Zt,eo,to,oo,no,so,io,ao,lo,co,po,mo,uo,fo],dependencies:{"fast-glob":"^3.3.2"}}});var gp,hp,yp,bp,wp,Tp=h(()=>{"use strict";l();gp="exec.run",hp="Run",yp="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",bp="execution",wp={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});import{execSync as tx}from"child_process";async function ox(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return tx(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"}):
58
59
  STDOUT:
59
60
  ${s}
60
61
  STDERR:
61
- ${i}`}}var bo,$s=h(()=>{"use strict";c();vp();S();bo={name:yp,displayName:bp,description:wp,parameters:xp,category:Tp,execute:ax,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var Cp,kp,Sp,Pp,_p,Rp=h(()=>{"use strict";c();Cp="exec.run_shell",kp="Run Shell",Sp="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",Pp="execution",_p={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});import{execSync as lx}from"child_process";function cx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function px(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return lx(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:cx()})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
62
+ ${i}`}}var go,Cs=h(()=>{"use strict";l();Tp();S();go={name:gp,displayName:hp,description:yp,parameters:wp,category:bp,execute:ox,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var xp,vp,Cp,kp,Sp,Pp=h(()=>{"use strict";l();xp="exec.run_shell",vp="Run Shell",Cp="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",kp="execution",Sp={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});import{execSync as nx}from"child_process";function rx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function sx(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");y(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return nx(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:rx()})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
62
63
  STDOUT:
63
64
  ${s}
64
65
  STDERR:
65
- ${i}`}}var wo,Es=h(()=>{"use strict";c();Rp();S();wo={name:Cp,displayName:kp,description:Sp,parameters:_p,category:Pp,execute:px,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});function $p(r,e,t){let o=`proc_${mx++}`,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",()=>{}),Fn.set(o,n),o}function Dt(r){return Fn.get(r)}function Ep(r){let e=Fn.get(r);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function Dp(){return Array.from(Fn.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 Fn,mx,Mt=h(()=>{"use strict";c();Fn=new Map,mx=1});var Mp,Ap,Np,Op,Ip,jp=h(()=>{"use strict";c();Mp="exec.run_background",Ap="Run Background",Np="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.",Op="execution",Ip={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});import{spawn as dx}from"child_process";async function ux(r){let e=r.command,t=r.cwd;if(!e)throw new Error("command is required");if(y(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let o=dx(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),n=$p(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 To,Ds=h(()=>{"use strict";c();Mt();jp();S();To={name:Mp,displayName:Ap,description:Np,parameters:Ip,category:Op,execute:ux,confirmation:{level:"medium",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var Lp,Fp,qp,Wp,Up,Gp=h(()=>{"use strict";c();Lp="exec.run_blocking",Fp="Run Blocking",qp="Execute a shell command and wait for it to finish naturally \u2014 no timeout. Use this for commands that take variable or unknown time (e.g. npm install, builds, tests). Returns exit code, stdout, and stderr when the process exits. For processes that never exit (servers, watchers), use exec.run_background instead.",Wp="execution",Up={type:"object",properties:{command:{type:"string",description:"The shell command to execute. Supports pipes, redirects, and shell features."},cwd:{type:"string",description:"Working directory for the command (optional). Defaults to the current working directory."}},required:["command"]}});import{spawn as fx}from"child_process";function gx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function hx(r){let e=r.command,t=r.cwd;if(!e)throw new Error("command is required");return y(`[exec.run-blocking] execute command="${e.substring(0,100)}" cwd=${t??"default"} (no timeout)`),new Promise(o=>{let n="",s="",i=fx(e,[],{cwd:t,shell:gx(),stdio:["ignore","pipe","pipe"]});i.stdout?.on("data",a=>{n+=a.toString(),n.length>2e6&&(n=n.slice(-1e6))}),i.stderr?.on("data",a=>{s+=a.toString(),s.length>2e6&&(s=s.slice(-1e6))}),i.on("close",a=>{let l=a??0;y(`[exec.run-blocking] finished exitCode=${l} stdout_len=${n.length} stderr_len=${s.length}`),o(JSON.stringify({exitCode:l,stdout:n||"(no output)",stderr:s||"",success:l===0}))}),i.on("error",a=>{y(`[exec.run-blocking] spawn error: ${a.message}`),o(JSON.stringify({exitCode:1,stdout:"",stderr:a.message,success:!1}))})})}var xo,Ms=h(()=>{"use strict";c();Gp();S();xo={name:Lp,displayName:Fp,description:qp,parameters:Up,category:Wp,execute:hx,confirmation:{level:"medium",reason:"This will execute a shell command and block until it completes.",showArgs:["command"]}}});var Bp,zp,Hp,Kp,Jp,Vp=h(()=>{"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 yx(r){let e=r.process_id;if(!e)throw new Error("process_id is required");let t=Dt(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 vo,As=h(()=>{"use strict";c();Mt();Vp();vo={name:Bp,displayName:zp,description:Hp,parameters:Jp,category:Kp,execute:yx}});var Qp,Xp,Yp,Zp,em,tm=h(()=>{"use strict";c();Qp="exec.tail_output",Xp="Tail Process Output",Yp="Read the last N lines of output from a background process started with exec.run_background. Use this to monitor long-running or non-exiting processes (e.g. dev servers, watchers) to detect ready signals, errors, or progress without reading all accumulated output. Returns alive status, exit code, and the most recent lines of stdout and stderr.",Zp="execution",em={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background."},lines:{type:"integer",description:"Number of lines to return from the end of stdout (default: 20).",default:20}},required:["process_id"]}});async function bx(r){let e=r.process_id,t=typeof r.lines=="number"?Math.max(1,Math.floor(r.lines)):20;if(!e)throw new Error("process_id is required");let o=Dt(e);if(!o)return JSON.stringify({error:`Process not found: ${e}`,hint:"Use exec.run_background to start a process first, then pass its id here."});let n=o.process.exitCode===null,s=o.process.exitCode,i=o.stdout.split(`
66
- `),a=i.slice(-t).join(`
67
- `).trim(),p=o.stderr.split(`
68
- `).filter(m=>m.trim()).slice(-3).join(`
69
- `).trim();return JSON.stringify({id:e,alive:n,exitCode:s,lastLines:a||"(no output yet)",lastStderr:p||"",totalStdoutLines:i.length})}var Co,Ns=h(()=>{"use strict";c();Mt();tm();Co={name:Qp,displayName:Xp,description:Yp,parameters:em,category:Zp,execute:bx}});var om,nm,rm,sm,im,am=h(()=>{"use strict";c();om="exec.kill",nm="Kill",rm="Kill a background process started with exec.run_background.",sm="execution",im={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function wx(r){let e=r.process_id;if(!e)throw new Error("process_id is required");let t=Dt(e);if(!t)throw new Error(`Process not found: ${e}`);return Ep(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var ko,Os=h(()=>{"use strict";c();Mt();am();ko={name:om,displayName:nm,description:rm,parameters:im,category:sm,execute:wx,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var lm,cm,pm,mm,dm,um=h(()=>{"use strict";c();lm="exec.list_processes",cm="List Processes",pm="List all managed background processes started with exec.run_background, including their status.",mm="execution",dm={type:"object",properties:{}}});async function Tx(r){let e=Dp();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var So,Is=h(()=>{"use strict";c();Mt();um();So={name:lm,displayName:cm,description:pm,parameters:dm,category:mm,execute:Tx}});var gm={};ne(gm,{execKillTool:()=>ko,execListProcessesTool:()=>So,execReadOutputTool:()=>vo,execRunBackgroundTool:()=>To,execRunBlockingTool:()=>xo,execRunShellTool:()=>wo,execRunTool:()=>bo,execTailOutputTool:()=>Co,execToolsProject:()=>fm});var fm,js=h(()=>{"use strict";c();$s();Es();Ds();Ms();As();Ns();Os();Is();$s();Es();Ds();Ms();As();Ns();Os();Is();fm={manifest:{key:"exec",name:"exec-tools",displayName:"Execution",version:"1.0.0",description:"Code execution tools for running commands, managing background processes, and automation.",author:"Sajeer",tools:["exec.run","exec.run_shell","exec.run_background","exec.run_blocking","exec.read_output","exec.tail_output","exec.kill","exec.list_processes"],category:"execution"},tools:[bo,wo,To,xo,vo,Co,ko,So],dependencies:{}}});var hm,ym,bm,wm,Tm,xm=h(()=>{"use strict";c();hm="system.info",ym="Info",bm="Get system information including OS, CPU, memory, and architecture.",wm="system",Tm={type:"object",properties:{}}});import*as q from"os";async function xx(r){return y("[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 Po,Ls=h(()=>{"use strict";c();xm();S();Po={name:hm,displayName:ym,description:bm,parameters:Tm,category:wm,execute:xx}});var vm,Cm,km,Sm,Pm,_m=h(()=>{"use strict";c();vm="system.env",Cm="Environment",km="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",Sm="system",Pm={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function vx(r){let e=r.key;if(y(`[system.env] execute key=${e??"all"}`),e){let n=process.env[e];return n===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:n})}let t={},o=Object.keys(process.env).sort();for(let n of o)process.env[n]!==void 0&&(t[n]=process.env[n]);return JSON.stringify(t,null,2)}var _o,Fs=h(()=>{"use strict";c();_m();S();_o={name:vm,displayName:Cm,description:km,parameters:Pm,category:Sm,execute:vx}});var Rm,$m,Em,Dm,Mm,Am=h(()=>{"use strict";c();Rm="system.set_env",$m="Set Environment",Em="Set an environment variable for the current session. Does not persist across restarts.",Dm="system",Mm={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function Cx(r){let e=r.key,t=r.value;if(!e)throw new Error("key is required");if(t==null)throw new Error("value is required");let o=process.env[e];return process.env[e]=t,o!==void 0?`Environment variable "${e}" updated (was: "${o}", now: "${t}")`:`Environment variable "${e}" set to "${t}"`}var Ro,qs=h(()=>{"use strict";c();Am();Ro={name:Rm,displayName:$m,description:Em,parameters:Mm,category:Dm,execute:Cx,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var Nm,Om,Im,jm,Lm,Fm=h(()=>{"use strict";c();Nm="system.cwd",Om="Current Directory",Im="Get the current working directory of the process.",jm="system",Lm={type:"object",properties:{}}});async function kx(r){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var $o,Ws=h(()=>{"use strict";c();Fm();S();$o={name:Nm,displayName:Om,description:Im,parameters:Lm,category:jm,execute:kx}});var qm,Wm,Um,Gm,Bm,zm=h(()=>{"use strict";c();qm="system.disk_usage",Wm="Disk Usage",Um="Get disk usage information for a given path or the root filesystem.",Gm="system",Bm={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});import*as Km from"fs";import*as Jm from"os";import*as qn from"path";import{execSync as Hm}from"child_process";function Us(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 Sx(r){let t=r.path||(process.platform==="win32"?Jm.tmpdir():"/");t=qn.resolve(t);let o=process.platform==="win32";try{let n=Km.statfsSync(t),s=BigInt(n.blocks)*BigInt(n.bsize),i=BigInt(n.bavail)*BigInt(n.bsize),a=BigInt(n.bfree)*BigInt(n.bsize),l=s-a,p=s>0?Number(l*BigInt(100)/s):0;return JSON.stringify({path:t,filesystem:"statfs",size:Us(Number(s)),used:Us(Number(l)),available:Us(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(n){try{if(o){let l=qn.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=Hm(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),d=JSON.parse(m.trim()),g=d.Total||0,b=d.Free||0,w=d.Used||0,T=g>0?Math.round(w/g*100):0;return JSON.stringify({path:t,filesystem:d.Name||"NTFS",size:`${(g/1024**3).toFixed(1)}G`,used:`${(w/1024**3).toFixed(1)}G`,available:`${(b/1024**3).toFixed(1)}G`,usePercent:`${T}%`,mountedOn:d.Drive||`${l}`},null,2)}let s=Hm(`df -h "${t}"`,{encoding:"utf-8",timeout:5e3}),i=s.trim().split(`
70
- `);if(i.length<2)return s;let a=i[1].split(/\s+/);return JSON.stringify({path:t,filesystem:a[0]||"unknown",size:a[1]||"unknown",used:a[2]||"unknown",available:a[3]||"unknown",usePercent:a[4]||"unknown",mountedOn:a[5]||"unknown"},null,2)}catch(s){throw new Error(`Failed to get disk usage for ${t}: ${n?.message||n}; fallback error: ${s.message}`)}}}var Eo,Gs=h(()=>{"use strict";c();zm();Eo={name:qm,displayName:Wm,description:Um,parameters:Bm,category:Gm,execute:Sx}});var Qm={};ne(Qm,{systemCwdTool:()=>$o,systemDiskUsageTool:()=>Eo,systemEnvTool:()=>_o,systemInfoTool:()=>Po,systemSetEnvTool:()=>Ro,systemToolsProject:()=>Vm});var Vm,Bs=h(()=>{"use strict";c();Ls();Fs();qs();Ws();Gs();Ls();Fs();qs();Ws();Gs();Vm={manifest:{key:"system",name:"system-tools",displayName:"System",version:"1.0.0",description:"System tools for querying OS info, environment variables, working directory, and disk usage.",author:"Sajeer",tools:["system.info","system.env","system.set_env","system.cwd","system.disk_usage"],category:"system"},tools:[Po,_o,Ro,$o,Eo],dependencies:{}}});var Xm,Ym,Zm,ed,td,od=h(()=>{"use strict";c();Xm="http.get",Ym="GET",Zm="Make an HTTP GET request to a URL and return the response body.",ed="network",td={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(y(`[http.get] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"GET",headers:t||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return o.ok?n.length>nd?`${s}
71
- ${n.substring(0,nd)}
66
+ ${i}`}}var ho,ks=h(()=>{"use strict";l();Pp();S();ho={name:xp,displayName:vp,description:Cp,parameters:Sp,category:kp,execute:sx,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});var _p,Rp,$p,Ep,Dp,Mp=h(()=>{"use strict";l();_p="exec.run_background",Rp="Run Background",$p="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.",Ep="execution",Dp={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});import{spawn as ix}from"child_process";async function ax(r,e){let t=r.command,o=r.cwd;if(!t)throw new Error("command is required");y(`[exec.run-background] execute command="${t.substring(0,100)}" cwd=${o??"default"}`);let n=ix(t,[],{cwd:o,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),i=(e?.processRegistry??$e).register(t,o,n);return JSON.stringify({id:i,pid:n.pid,command:t,message:`Background process started. Use exec.read_output("${i}") to read output, exec.kill("${i}") to stop.`})}var yo,Ss=h(()=>{"use strict";l();nt();Mp();S();yo={name:_p,displayName:Rp,description:$p,parameters:Dp,category:Ep,execute:ax,confirmation:{level:"medium",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var Ap,Np,Op,Ip,Lp,jp=h(()=>{"use strict";l();Ap="exec.run_blocking",Np="Run Blocking",Op="Execute a shell command and wait for it to finish naturally \u2014 no timeout. Use this for commands that take variable or unknown time (e.g. npm install, builds, tests). Returns exit code, stdout, and stderr when the process exits. For processes that never exit (servers, watchers), use exec.run_background instead.",Ip="execution",Lp={type:"object",properties:{command:{type:"string",description:"The shell command to execute. Supports pipes, redirects, and shell features."},cwd:{type:"string",description:"Working directory for the command (optional). Defaults to the current working directory."}},required:["command"]}});import{spawn as lx}from"child_process";function cx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function px(r){let e=r.command,t=r.cwd;if(!e)throw new Error("command is required");return y(`[exec.run-blocking] execute command="${e.substring(0,100)}" cwd=${t??"default"} (no timeout)`),new Promise(o=>{let n="",s="",i=lx(e,[],{cwd:t,shell:cx(),stdio:["ignore","pipe","pipe"]});i.stdout?.on("data",a=>{n+=a.toString(),n.length>2e6&&(n=n.slice(-1e6))}),i.stderr?.on("data",a=>{s+=a.toString(),s.length>2e6&&(s=s.slice(-1e6))}),i.on("close",a=>{let c=a??0;y(`[exec.run-blocking] finished exitCode=${c} stdout_len=${n.length} stderr_len=${s.length}`),o(JSON.stringify({exitCode:c,stdout:n||"(no output)",stderr:s||"",success:c===0}))}),i.on("error",a=>{y(`[exec.run-blocking] spawn error: ${a.message}`),o(JSON.stringify({exitCode:1,stdout:"",stderr:a.message,success:!1}))})})}var bo,Ps=h(()=>{"use strict";l();jp();S();bo={name:Ap,displayName:Np,description:Op,parameters:Lp,category:Ip,execute:px,confirmation:{level:"medium",reason:"This will execute a shell command and block until it completes.",showArgs:["command"]}}});var Fp,qp,Wp,Up,Gp,Bp=h(()=>{"use strict";l();Fp="exec.read_output",qp="Read Output",Wp="Read stdout and stderr from a background process started with exec.run_background.",Up="execution",Gp={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function mx(r,e){let t=r.process_id;if(!t)throw new Error("process_id is required");let n=(e?.processRegistry??$e).get(t);if(!n)throw new Error(`Process not found: ${t}`);let s=n.process.exitCode===null;return JSON.stringify({id:n.id,alive:s,exitCode:n.process.exitCode,stdout:n.stdout,stderr:n.stderr})}var wo,_s=h(()=>{"use strict";l();nt();Bp();wo={name:Fp,displayName:qp,description:Wp,parameters:Gp,category:Up,execute:mx}});var zp,Hp,Kp,Jp,Vp,Qp=h(()=>{"use strict";l();zp="exec.tail_output",Hp="Tail Process Output",Kp="Read the last N lines of output from a background process started with exec.run_background. Use this to monitor long-running or non-exiting processes (e.g. dev servers, watchers) to detect ready signals, errors, or progress without reading all accumulated output. Returns alive status, exit code, and the most recent lines of stdout and stderr.",Jp="execution",Vp={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background."},lines:{type:"integer",description:"Number of lines to return from the end of stdout (default: 20).",default:20}},required:["process_id"]}});async function dx(r,e){let t=r.process_id,o=typeof r.lines=="number"?Math.max(1,Math.floor(r.lines)):20;if(!t)throw new Error("process_id is required");let s=(e?.processRegistry??$e).get(t);if(!s)return JSON.stringify({error:`Process not found: ${t}`,hint:"Use exec.run_background to start a process first, then pass its id here."});let i=s.process.exitCode===null,a=s.process.exitCode,c=s.stdout.split(`
67
+ `),p=c.slice(-o).join(`
68
+ `).trim(),d=s.stderr.split(`
69
+ `).filter(g=>g.trim()).slice(-3).join(`
70
+ `).trim();return JSON.stringify({id:t,alive:i,exitCode:a,lastLines:p||"(no output yet)",lastStderr:d||"",totalStdoutLines:c.length})}var To,Rs=h(()=>{"use strict";l();nt();Qp();To={name:zp,displayName:Hp,description:Kp,parameters:Vp,category:Jp,execute:dx}});var Xp,Yp,Zp,em,tm,om=h(()=>{"use strict";l();Xp="exec.kill",Yp="Kill",Zp="Kill a background process started with exec.run_background.",em="execution",tm={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function ux(r,e){let t=r.process_id;if(!t)throw new Error("process_id is required");let o=e?.processRegistry??$e,n=o.get(t);if(!n)throw new Error(`Process not found: ${t}`);return o.kill(t)?`Process ${t} (${n.command}) killed successfully.`:`Process ${t} (${n.command}) was already terminated (exit code: ${n.process.exitCode}).`}var xo,$s=h(()=>{"use strict";l();nt();om();xo={name:Xp,displayName:Yp,description:Zp,parameters:tm,category:em,execute:ux,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var nm,rm,sm,im,am,lm=h(()=>{"use strict";l();nm="exec.list_processes",rm="List Processes",sm="List all managed background processes started with exec.run_background, including their status.",im="execution",am={type:"object",properties:{}}});async function fx(r,e){let o=(e?.processRegistry??$e).list();return o.length===0?"No managed background processes.":JSON.stringify(o,null,2)}var vo,Es=h(()=>{"use strict";l();nt();lm();vo={name:nm,displayName:rm,description:sm,parameters:am,category:im,execute:fx}});var pm={};oe(pm,{execKillTool:()=>xo,execListProcessesTool:()=>vo,execReadOutputTool:()=>wo,execRunBackgroundTool:()=>yo,execRunBlockingTool:()=>bo,execRunShellTool:()=>ho,execRunTool:()=>go,execTailOutputTool:()=>To,execToolsProject:()=>cm});var cm,Ds=h(()=>{"use strict";l();Cs();ks();Ss();Ps();_s();Rs();$s();Es();Cs();ks();Ss();Ps();_s();Rs();$s();Es();cm={manifest:{key:"exec",name:"exec-tools",displayName:"Execution",version:"1.0.0",description:"Code execution tools for running commands, managing background processes, and automation.",author:"Sajeer",tools:["exec.run","exec.run_shell","exec.run_background","exec.run_blocking","exec.read_output","exec.tail_output","exec.kill","exec.list_processes"],category:"execution"},tools:[go,ho,yo,bo,wo,To,xo,vo],dependencies:{}}});var mm,dm,um,fm,gm,hm=h(()=>{"use strict";l();mm="system.info",dm="Info",um="Get system information including OS, CPU, memory, and architecture.",fm="system",gm={type:"object",properties:{}}});import*as L from"os";async function gx(r){return y("[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 Co,Ms=h(()=>{"use strict";l();hm();S();Co={name:mm,displayName:dm,description:um,parameters:gm,category:fm,execute:gx}});var ym,bm,wm,Tm,xm,vm=h(()=>{"use strict";l();ym="system.env",bm="Environment",wm="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",Tm="system",xm={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function hx(r){let e=r.key;if(y(`[system.env] execute key=${e??"all"}`),e){let n=process.env[e];return n===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:n})}let t={},o=Object.keys(process.env).sort();for(let n of o)process.env[n]!==void 0&&(t[n]=process.env[n]);return JSON.stringify(t,null,2)}var ko,As=h(()=>{"use strict";l();vm();S();ko={name:ym,displayName:bm,description:wm,parameters:xm,category:Tm,execute:hx}});var Cm,km,Sm,Pm,_m,Rm=h(()=>{"use strict";l();Cm="system.set_env",km="Set Environment",Sm="Set an environment variable for the current session. Does not persist across restarts.",Pm="system",_m={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function yx(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,Ns=h(()=>{"use strict";l();Rm();So={name:Cm,displayName:km,description:Sm,parameters:_m,category:Pm,execute:yx,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var $m,Em,Dm,Mm,Am,Nm=h(()=>{"use strict";l();$m="system.cwd",Em="Current Directory",Dm="Get the current working directory of the process.",Mm="system",Am={type:"object",properties:{}}});async function bx(r){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var Po,Os=h(()=>{"use strict";l();Nm();S();Po={name:$m,displayName:Em,description:Dm,parameters:Am,category:Mm,execute:bx}});var Om,Im,Lm,jm,Fm,qm=h(()=>{"use strict";l();Om="system.disk_usage",Im="Disk Usage",Lm="Get disk usage information for a given path or the root filesystem.",jm="system",Fm={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});import*as Um from"fs";import*as Gm from"os";import*as On from"path";import{execSync as Wm}from"child_process";function Is(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 wx(r){let t=r.path||(process.platform==="win32"?Gm.tmpdir():"/");t=On.resolve(t);let o=process.platform==="win32";try{let n=Um.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:Is(Number(s)),used:Is(Number(c)),available:Is(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(n){try{if(o){let c=On.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=Wm(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),d=JSON.parse(m.trim()),g=d.Total||0,w=d.Free||0,b=d.Used||0,T=g>0?Math.round(b/g*100):0;return JSON.stringify({path:t,filesystem:d.Name||"NTFS",size:`${(g/1024**3).toFixed(1)}G`,used:`${(b/1024**3).toFixed(1)}G`,available:`${(w/1024**3).toFixed(1)}G`,usePercent:`${T}%`,mountedOn:d.Drive||`${c}`},null,2)}let s=Wm(`df -h "${t}"`,{encoding:"utf-8",timeout:5e3}),i=s.trim().split(`
71
+ `);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 _o,Ls=h(()=>{"use strict";l();qm();_o={name:Om,displayName:Im,description:Lm,parameters:Fm,category:jm,execute:wx}});var zm={};oe(zm,{systemCwdTool:()=>Po,systemDiskUsageTool:()=>_o,systemEnvTool:()=>ko,systemInfoTool:()=>Co,systemSetEnvTool:()=>So,systemToolsProject:()=>Bm});var Bm,js=h(()=>{"use strict";l();Ms();As();Ns();Os();Ls();Ms();As();Ns();Os();Ls();Bm={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:[Co,ko,So,Po,_o],dependencies:{}}});var Hm,Km,Jm,Vm,Qm,Xm=h(()=>{"use strict";l();Hm="http.get",Km="GET",Jm="Make an HTTP GET request to a URL and return the response body.",Vm="network",Qm={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 Tx(r){let e=r.url,t=r.headers;if(y(`[http.get] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"GET",headers:t||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return o.ok?n.length>Ym?`${s}
72
+ ${n.substring(0,Ym)}
72
73
 
73
74
  ... (truncated, total ${n.length} characters)`:`${s}
74
75
  ${n}`:`${s}
75
- ${n}`}var nd,Do,zs=h(()=>{"use strict";c();od();S();nd=1e5;Do={name:Xm,displayName:Ym,description:Zm,parameters:td,category:ed,execute:Px}});var rd,sd,id,ad,ld,cd=h(()=>{"use strict";c();rd="http.post",sd="POST",id="Make an HTTP POST request to a URL with an optional body and return the response.",ad="network",ld={type:"object",properties:{url:{type:"string",description:"The URL to request"},body:{type:"string",description:"Request body (JSON string or plain text)"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function _x(r){let e=r.url,t=r.body,o=r.headers||{};if(y(`[http.post] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let n=await fetch(e,{method:"POST",headers:o,body:t||void 0}),s=await n.text(),i=`HTTP ${n.status} ${n.statusText}`;return s.length>pd?`${i}
76
- ${s.substring(0,pd)}
76
+ ${n}`}var Ym,Ro,Fs=h(()=>{"use strict";l();Xm();S();Ym=1e5;Ro={name:Hm,displayName:Km,description:Jm,parameters:Qm,category:Vm,execute:Tx}});var Zm,ed,td,od,nd,rd=h(()=>{"use strict";l();Zm="http.post",ed="POST",td="Make an HTTP POST request to a URL with an optional body and return the response.",od="network",nd={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 xx(r){let e=r.url,t=r.body,o=r.headers||{};if(y(`[http.post] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let n=await fetch(e,{method:"POST",headers:o,body:t||void 0}),s=await n.text(),i=`HTTP ${n.status} ${n.statusText}`;return s.length>sd?`${i}
77
+ ${s.substring(0,sd)}
77
78
 
78
79
  ... (truncated, total ${s.length} characters)`:`${i}
79
- ${s}`}var pd,Mo,Hs=h(()=>{"use strict";c();cd();S();pd=1e5;Mo={name:rd,displayName:sd,description:id,parameters:ld,category:ad,execute:_x,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var md,dd,ud,fd,gd,hd=h(()=>{"use strict";c();md="http.put",dd="PUT",ud="Make an HTTP PUT request to a URL with an optional body and return the response.",fd="network",gd={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 Rx(r){let e=r.url,t=r.body,o=r.headers||{};if(y(`[http.put] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let n=await fetch(e,{method:"PUT",headers:o,body:t||void 0}),s=await n.text(),i=`HTTP ${n.status} ${n.statusText}`;return s.length>yd?`${i}
80
- ${s.substring(0,yd)}
80
+ ${s}`}var sd,$o,qs=h(()=>{"use strict";l();rd();S();sd=1e5;$o={name:Zm,displayName:ed,description:td,parameters:nd,category:od,execute:xx,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var id,ad,ld,cd,pd,md=h(()=>{"use strict";l();id="http.put",ad="PUT",ld="Make an HTTP PUT request to a URL with an optional body and return the response.",cd="network",pd={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 vx(r){let e=r.url,t=r.body,o=r.headers||{};if(y(`[http.put] execute url="${e}" body_len=${t?.length??0}`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");if(t&&!o["Content-Type"]&&!o["content-type"])try{JSON.parse(t),o["Content-Type"]="application/json"}catch{o["Content-Type"]="text/plain"}let n=await fetch(e,{method:"PUT",headers:o,body:t||void 0}),s=await n.text(),i=`HTTP ${n.status} ${n.statusText}`;return s.length>dd?`${i}
81
+ ${s.substring(0,dd)}
81
82
 
82
83
  ... (truncated)`:`${i}
83
- ${s}`}var yd,Ao,Ks=h(()=>{"use strict";c();hd();S();yd=1e5;Ao={name:md,displayName:dd,description:ud,parameters:gd,category:fd,execute:Rx,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var bd,wd,Td,xd,vd,Cd=h(()=>{"use strict";c();bd="http.delete",wd="DELETE",Td="Make an HTTP DELETE request to a URL and return the response.",xd="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 $x(r){let e=r.url,t=r.headers;if(y(`[http.delete] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"DELETE",headers:t||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return n.length>kd?`${s}
84
- ${n.substring(0,kd)}
84
+ ${s}`}var dd,Eo,Ws=h(()=>{"use strict";l();md();S();dd=1e5;Eo={name:id,displayName:ad,description:ld,parameters:pd,category:cd,execute:vx,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var ud,fd,gd,hd,yd,bd=h(()=>{"use strict";l();ud="http.delete",fd="DELETE",gd="Make an HTTP DELETE request to a URL and return the response.",hd="network",yd={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 Cx(r){let e=r.url,t=r.headers;if(y(`[http.delete] execute url="${e}"`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=await fetch(e,{method:"DELETE",headers:t||{}}),n=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return n.length>wd?`${s}
85
+ ${n.substring(0,wd)}
85
86
 
86
87
  ... (truncated)`:`${s}
87
- ${n}`}var kd,No,Js=h(()=>{"use strict";c();Cd();S();kd=1e5;No={name:bd,displayName:wd,description:Td,parameters:vd,category:xd,execute:$x,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var Sd,Pd,_d,Rd,$d,Ed=h(()=>{"use strict";c();Sd="http.download",Pd="Download",_d="Download a file from a URL and save it to a local path.",Rd="network",$d={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});import*as At from"fs";import*as Dd from"path";async function Ex(r){let e=r.url,t=r.path,o=r.headers;if(y(`[http.download] execute url="${e}" path="${t}"`),!e)throw new Error("url is required");if(!t)throw new Error("path is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let n=await fetch(e,{method:"GET",headers:o||{}});if(!n.ok)throw new Error(`Download failed: HTTP ${n.status} ${n.statusText}`);let s=Buffer.from(await n.arrayBuffer()),i=Dd.dirname(t);return At.existsSync(i)||At.mkdirSync(i,{recursive:!0}),At.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var Oo,Vs=h(()=>{"use strict";c();Ed();S();Oo={name:Sd,displayName:Pd,description:_d,parameters:$d,category:Rd,execute:Ex}});var Ad={};ne(Ad,{httpDeleteTool:()=>No,httpDownloadTool:()=>Oo,httpGetTool:()=>Do,httpPostTool:()=>Mo,httpPutTool:()=>Ao,httpToolsProject:()=>Md});var Md,Qs=h(()=>{"use strict";c();zs();Hs();Ks();Js();Vs();zs();Hs();Ks();Js();Vs();Md={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:[Do,Mo,Ao,No,Oo],dependencies:{}}});var Nd,Od,Id,jd,Ld,Fd=h(()=>{"use strict";c();Nd="github.graphql.execute",Od="GitHub GraphQL",Id=["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(" "),jd="github",Ld={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 V(r,e){let t={Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...e||{}};return r&&(t.Authorization=`Bearer ${r}`),t}var $e=h(()=>{"use strict";c()});import*as Ud from"crypto";async function B(r,e){if(e)return e;let t=process.env.GITHUB_PAT;if(t)return t;let o=process.env.GITHUB_APP_ID,n=process.env.GITHUB_APP_PRIVATE_KEY?.replace(/\\n/g,`
88
- `);if(!o||!n)throw new Error("No GitHub token available. Set GITHUB_PAT, or GITHUB_APP_ID + GITHUB_APP_PRIVATE_KEY.");let s=await Dx(o,n,r);return Mx(o,n,s)}async function Dx(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=Wd.get(t);if(o!==void 0)return o;let n=Gd(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 Wd.set(t,i.id),i.id}async function Mx(r,e,t){let o=qd.get(t);if(o&&o.expiresAt>Date.now()+6e4)return o.token;let n=Gd(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 qd.set(t,{token:i.token,expiresAt:new Date(i.expires_at).getTime()}),i.token}function Gd(r,e){let t=Math.floor(Date.now()/1e3),o={alg:"RS256",typ:"JWT"},n={iat:t-30,exp:t+540,iss:r},s=l=>Buffer.from(JSON.stringify(l)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),i=`${s(o)}.${s(n)}`,a=Ud.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var qd,Wd,ke=h(()=>{"use strict";c();qd=new Map,Wd=new Map});async function Ax(r){let e=r.query,t=r.variables??{},o=await B(r.repo,r.token);y(`[github.graphql.execute] query_len=${e?.length??0}`);let n=await fetch("https://api.github.com/graphql",{method:"POST",headers:V(o,{"Content-Type":"application/json"}),body:JSON.stringify({query:e,variables:t})}),s=await n.text();try{let i=JSON.parse(s);i&&Array.isArray(i.errors)&&i.errors.length>0&&y(`[github.graphql.execute] errors=${i.errors.length}`)}catch{}return`HTTP ${n.status} ${n.statusText}
89
- ${s}`}var Io,Xs=h(()=>{"use strict";c();Fd();S();$e();ke();Io={name:Nd,displayName:Od,description:Id,parameters:Ld,category:jd,execute:Ax}});var Bd,zd,Hd,Kd,Jd,Vd=h(()=>{"use strict";c();Bd="github.contents.getText",zd="Get Repo File (Text)",Hd="Fetch file content (decoded text) via the GitHub Contents API.",Kd="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"]}});import{Buffer as Wn}from"buffer";async function Nx(r){let e=r.repo,t=r.path,o=r.ref,n=await B(e,r.token),s=r.maxBytes?Number(r.maxBytes):void 0,i=t.split("/").map(m=>encodeURIComponent(m)).join("/"),a=`https://api.github.com/repos/${e}/contents/${i}${o?`?ref=${encodeURIComponent(o)}`:""}`;y(`[github.contents.getText] repo=${e} path=${t} ref=${o??""}`);let l=await fetch(a,{method:"GET",headers:V(n)}),p=await l.text();if(!l.ok)return`HTTP ${l.status} ${l.statusText}
90
- ${p}`;try{let d=JSON.parse(p)?.content;if(typeof d=="string"){let g=Wn.from(d.replace(/\n/g,""),"base64").toString("utf8");if(s&&Wn.byteLength(g,"utf8")>s){let b=Wn.from(g,"utf8").subarray(0,s).toString("utf8"),w=`
91
- \u2026 [truncated, ${s} of ${Wn.byteLength(g,"utf8")} bytes]`;return`HTTP ${l.status} ${l.statusText}
92
- ${b}${w}`}return`HTTP ${l.status} ${l.statusText}
93
- ${g}`}}catch{}return`HTTP ${l.status} ${l.statusText}
94
- ${p}`}var jo,Ys=h(()=>{"use strict";c();Vd();S();$e();ke();jo={name:Bd,displayName:zd,description:Hd,parameters:Jd,category:Kd,execute:Nx}});var Qd,Xd,Yd,Zd,eu,tu=h(()=>{"use strict";c();Qd="github.pr.reviewThreads.list",Xd="List PR Review Threads",Yd="List PR review threads via GraphQL (optionally unresolved only).",Zd="github",eu={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 Ox(r){let[e,t]=String(r.repo).split("/"),o=Number(r.number),n=await B(r.repo,r.token),s=!!r.unresolvedOnly,i=r.first?Number(r.first):100,a=r.after?String(r.after):void 0,l=r.commentsFirst?Number(r.commentsFirst):20,p=!!r.includeMeta;y(`[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:V(n,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
88
+ ${n}`}var wd,Do,Us=h(()=>{"use strict";l();bd();S();wd=1e5;Do={name:ud,displayName:fd,description:gd,parameters:yd,category:hd,execute:Cx,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var Td,xd,vd,Cd,kd,Sd=h(()=>{"use strict";l();Td="http.download",xd="Download",vd="Download a file from a URL and save it to a local path.",Cd="network",kd={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});import*as Dt from"fs";import*as Pd from"path";async function kx(r){let e=r.url,t=r.path,o=r.headers;if(y(`[http.download] execute url="${e}" path="${t}"`),!e)throw new Error("url is required");if(!t)throw new Error("path is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let n=await fetch(e,{method:"GET",headers:o||{}});if(!n.ok)throw new Error(`Download failed: HTTP ${n.status} ${n.statusText}`);let s=Buffer.from(await n.arrayBuffer()),i=Pd.dirname(t);return Dt.existsSync(i)||Dt.mkdirSync(i,{recursive:!0}),Dt.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var Mo,Gs=h(()=>{"use strict";l();Sd();S();Mo={name:Td,displayName:xd,description:vd,parameters:kd,category:Cd,execute:kx}});var Rd={};oe(Rd,{httpDeleteTool:()=>Do,httpDownloadTool:()=>Mo,httpGetTool:()=>Ro,httpPostTool:()=>$o,httpPutTool:()=>Eo,httpToolsProject:()=>_d});var _d,Bs=h(()=>{"use strict";l();Fs();qs();Ws();Us();Gs();Fs();qs();Ws();Us();Gs();_d={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:[Ro,$o,Eo,Do,Mo],dependencies:{}}});var $d,Ed,Dd,Md,Ad,Nd=h(()=>{"use strict";l();$d="github.graphql.execute",Ed="GitHub GraphQL",Dd=["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(" "),Md="github",Ad={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 V(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 Ee=h(()=>{"use strict";l()});async function Sx(r,e){let t=r.query,o=r.variables??{},n=await B(r.repo,r.token,e?.githubTokenStore,e?.config?.credentials);y(`[github.graphql.execute] query_len=${t?.length??0}`);let s=await fetch("https://api.github.com/graphql",{method:"POST",headers:V(n,{"Content-Type":"application/json"}),body:JSON.stringify({query:t,variables:o})}),i=await s.text();try{let a=JSON.parse(i);a&&Array.isArray(a.errors)&&a.errors.length>0&&y(`[github.graphql.execute] errors=${a.errors.length}`)}catch{}return`HTTP ${s.status} ${s.statusText}
89
+ ${i}`}var Ao,zs=h(()=>{"use strict";l();Nd();S();Ee();be();Ao={name:$d,displayName:Ed,description:Dd,parameters:Ad,category:Md,execute:Sx}});var Od,Id,Ld,jd,Fd,qd=h(()=>{"use strict";l();Od="github.contents.getText",Id="Get Repo File (Text)",Ld="Fetch file content (decoded text) via the GitHub Contents API.",jd="github",Fd={type:"object",properties:{repo:{type:"string",description:"owner/name (e.g. octo/repo)"},path:{type:"string",description:"File path within the repo"},ref:{type:"string",description:"Branch, tag, or commit sha"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of decoded text to return; if exceeded, result is truncated with a footer."}},required:["repo","path"]}});import{Buffer as In}from"buffer";async function Px(r,e){let t=r.repo,o=r.path,n=r.ref,s=await B(t,r.token,e?.githubTokenStore,e?.config?.credentials),i=r.maxBytes?Number(r.maxBytes):void 0,a=o.split("/").map(d=>encodeURIComponent(d)).join("/"),c=`https://api.github.com/repos/${t}/contents/${a}${n?`?ref=${encodeURIComponent(n)}`:""}`;y(`[github.contents.getText] repo=${t} path=${o} ref=${n??""}`);let p=await fetch(c,{method:"GET",headers:V(s)}),m=await p.text();if(!p.ok)return`HTTP ${p.status} ${p.statusText}
90
+ ${m}`;try{let g=JSON.parse(m)?.content;if(typeof g=="string"){let w=In.from(g.replace(/\n/g,""),"base64").toString("utf8");if(i&&In.byteLength(w,"utf8")>i){let b=In.from(w,"utf8").subarray(0,i).toString("utf8"),T=`
91
+ \u2026 [truncated, ${i} of ${In.byteLength(w,"utf8")} bytes]`;return`HTTP ${p.status} ${p.statusText}
92
+ ${b}${T}`}return`HTTP ${p.status} ${p.statusText}
93
+ ${w}`}}catch{}return`HTTP ${p.status} ${p.statusText}
94
+ ${m}`}var No,Hs=h(()=>{"use strict";l();qd();S();Ee();be();No={name:Od,displayName:Id,description:Ld,parameters:Fd,category:jd,execute:Px}});var Wd,Ud,Gd,Bd,zd,Hd=h(()=>{"use strict";l();Wd="github.pr.reviewThreads.list",Ud="List PR Review Threads",Gd="List PR review threads via GraphQL (optionally unresolved only).",Bd="github",zd={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 _x(r,e){let[t,o]=String(r.repo).split("/"),n=Number(r.number),s=await B(r.repo,r.token,e?.githubTokenStore,e?.config?.credentials),i=!!r.unresolvedOnly,a=r.first?Number(r.first):100,c=r.after?String(r.after):void 0,p=r.commentsFirst?Number(r.commentsFirst):20,m=!!r.includeMeta;y(`[github.pr.reviewThreads.list] repo=${t}/${o} pr=${n} unresolvedOnly=${i} first=${a} after=${c??""} commentsFirst=${p} includeMeta=${m}`);let g=await fetch("https://api.github.com/graphql",{method:"POST",headers:V(s,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
95
95
  repository(owner:$owner,name:$name){
96
96
  pullRequest(number:$number){
97
97
  headRefOid
@@ -101,29 +101,29 @@ ${p}`}var jo,Ys=h(()=>{"use strict";c();Vd();S();$e();ke();jo={name:Bd,displayNa
101
101
  }
102
102
  }
103
103
  }
104
- }`,variables:{owner:e,name:t,number:o,first:i,after:a,commentsFirst:l}})}),g=await d.text();if(!d.ok)return`HTTP ${d.status} ${d.statusText}
105
- ${g}`;try{let b=JSON.parse(g);b&&Array.isArray(b.errors)&&b.errors.length>0&&y(`[github.pr.reviewThreads.list] errors=${b.errors.length}`);let w=b?.data?.repository?.pullRequest,T=w?.reviewThreads?.pageInfo??{hasNextPage:!1,endCursor:null},v=w?.reviewThreads?.nodes??[];if(s&&(v=v.filter(C=>C?.isResolved===!1)),p){let C={headRefOid:w?.headRefOid,threads:v,pageInfo:T};return`HTTP 200 OK
106
- ${JSON.stringify(C)}`}return`HTTP 200 OK
107
- ${JSON.stringify(v)}`}catch{return`HTTP ${d.status} ${d.statusText}
108
- ${g}`}}var Lo,Zs=h(()=>{"use strict";c();tu();$e();S();ke();Lo={name:Qd,displayName:Xd,description:Yd,parameters:eu,category:Zd,execute:Ox}});var ou,nu,ru,su,iu,au=h(()=>{"use strict";c();ou="github.pr.reviewThreads.resolve",nu="Resolve Review Thread",ru=["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(" "),su="github",iu={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 Ix(r){let e=String(r.threadId),t=await B(r.repo,r.token);y(`[github.pr.reviewThreads.resolve] threadId=${e}`);let n=await fetch("https://api.github.com/graphql",{method:"POST",headers:V(t,{"Content-Type":"application/json"}),body:JSON.stringify({query:"mutation($id:ID!){ resolveReviewThread(input:{threadId:$id}) { thread { id isResolved } } }",variables:{id:e}})}),s=await n.text();if(n.ok)try{if(JSON.parse(s).errors?.find(l=>l.type==="FORBIDDEN"))return["TOOL_UNSUPPORTED_FOR_TOKEN_TYPE: resolveReviewThread is not available for GitHub App installation tokens (ghs_*).","GitHub requires a user identity (PAT with repo scope) for this operation.","Fallback action: post a reply on the thread acknowledging the fix and ask the author to resolve it manually."].join(" ")}catch{}return`HTTP ${n.status} ${n.statusText}
109
- ${s}`}var Fo,ei=h(()=>{"use strict";c();au();$e();S();ke();Fo={name:ou,displayName:nu,description:ru,parameters:iu,category:su,execute:Ix}});var lu,cu,pu,mu,du,uu=h(()=>{"use strict";c();lu="github.pr.reviewComments.reply",cu="Reply to Review Comment",pu="Reply within an existing PR review thread to maintain continuity.",mu="github",du={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 jx(r){let e=String(r.repo),t=Number(r.number),o=Number(r.inReplyTo),n=String(r.body),s=await B(e,r.token),i=`https://api.github.com/repos/${e}/pulls/${t}/comments/${o}/replies`;y(`[github.pr.reviewComments.reply] repo=${e} inReplyTo=${o}`);let a=await fetch(i,{method:"POST",headers:V(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),l=await a.text();return`HTTP ${a.status} ${a.statusText}
110
- ${l}`}var qo,ti=h(()=>{"use strict";c();uu();S();$e();ke();qo={name:lu,displayName:cu,description:pu,parameters:du,category:mu,execute:jx}});var fu,gu,hu,yu,bu,wu=h(()=>{"use strict";c();fu="github.pr.diff.get",gu="Get PR Diff",hu="Fetch the unified diff for a pull request (text/patch).",yu="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"]}});import{Buffer as oi}from"buffer";async function Lx(r){let e=String(r.repo),t=Number(r.number),o=await B(e,r.token),n=r.maxBytes?Number(r.maxBytes):void 0,s=`https://api.github.com/repos/${e}/pulls/${t}`;y(`[github.pr.diff.get] repo=${e} pr=${t}`);let i=await fetch(s,{method:"GET",headers:V(o,{Accept:"application/vnd.github.v3.diff"})}),a=await i.text();if(n&&oi.byteLength(a,"utf8")>n){let l=oi.from(a,"utf8").subarray(0,n).toString("utf8"),p=`
111
- \u2026 [truncated, ${n} of ${oi.byteLength(a,"utf8")} bytes]`;return`HTTP ${i.status} ${i.statusText}
112
- ${l}${p}`}return`HTTP ${i.status} ${i.statusText}
113
- ${a}`}var Wo,ni=h(()=>{"use strict";c();wu();$e();S();ke();Wo={name:fu,displayName:gu,description:hu,parameters:bu,category:yu,execute:Lx}});var Tu,xu,vu,Cu,ku,Su=h(()=>{"use strict";c();Tu="github.pr.files.list",xu="List PR Files",vu="List files changed in a PR with positions metadata.",Cu="github",ku={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 Fx(r){let e=String(r.repo),t=Number(r.number),o=await B(e,r.token),n=r.perPage?Number(r.perPage):void 0,s=r.page?Number(r.page):void 0,i=new URLSearchParams;n&&i.set("per_page",String(n)),s&&i.set("page",String(s));let a=`https://api.github.com/repos/${e}/pulls/${t}/files${i.toString()?`?${i.toString()}`:""}`;y(`[github.pr.files.list] repo=${e} pr=${t} perPage=${n??""} page=${s??""}`);let l=await fetch(a,{method:"GET",headers:V(o)}),p=await l.text();return`HTTP ${l.status} ${l.statusText}
114
- ${p}`}var Uo,ri=h(()=>{"use strict";c();Su();$e();S();ke();Uo={name:Tu,displayName:xu,description:vu,parameters:ku,category:Cu,execute:Fx}});var Pu,_u,Ru,$u,Eu,Du=h(()=>{"use strict";c();Pu="github.pr.reviews.submit",_u="Submit PR Review",Ru="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",$u="github",Eu={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 qx(r){let e=String(r.repo),t=Number(r.number),o=String(r.event),n=r.body?String(r.body):void 0,s=Array.isArray(r.comments)?r.comments:void 0,i=await B(e,r.token),a=`https://api.github.com/repos/${e}/pulls/${t}/reviews`;y(`[github.pr.reviews.submit] repo=${e} pr=${t} event=${o} comments=${s?.length??0}`);let l={event:o};n&&(l.body=n),s&&s.length>0&&(l.comments=s);let p=await fetch(a,{method:"POST",headers:V(i,{"Content-Type":"application/json"}),body:JSON.stringify(l)}),m=await p.text();return`HTTP ${p.status} ${p.statusText}
115
- ${m}`}var Go,si=h(()=>{"use strict";c();Du();$e();S();ke();Go={name:Pu,displayName:_u,description:Ru,parameters:Eu,category:$u,execute:qx}});var Mu,Au,Nu,Ou,Iu,ju=h(()=>{"use strict";c();Mu="github.issues.comments.create",Au="Create Issue/PR Comment",Nu="Create a comment on an issue or pull request (conversation tab).",Ou="github",Iu={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 Wx(r){let e=String(r.repo),t=Number(r.number),o=String(r.body),n=await B(e,r.token),s=`https://api.github.com/repos/${e}/issues/${t}/comments`;y(`[github.issues.comments.create] repo=${e} number=${t}`);let i=await fetch(s,{method:"POST",headers:V(n,{"Content-Type":"application/json"}),body:JSON.stringify({body:o})}),a=await i.text();return`HTTP ${i.status} ${i.statusText}
116
- ${a}`}var Bo,ii=h(()=>{"use strict";c();ju();$e();S();ke();Bo={name:Mu,displayName:Au,description:Nu,parameters:Iu,category:Ou,execute:Wx}});var Fu={};ne(Fu,{githubContentsGetTextTool:()=>jo,githubGraphqlExecuteTool:()=>Io,githubIssuesCommentsCreateTool:()=>Bo,githubPrDiffGetTool:()=>Wo,githubPrFilesListTool:()=>Uo,githubPrReviewCommentsReplyTool:()=>qo,githubPrReviewThreadsListTool:()=>Lo,githubPrReviewThreadsResolveTool:()=>Fo,githubPrReviewsSubmitTool:()=>Go,githubToolsProject:()=>Lu});var Lu,ai=h(()=>{"use strict";c();Xs();Ys();Zs();ei();ti();ni();ri();si();ii();Xs();Ys();Zs();ei();ti();ni();ri();si();ii();Lu={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:[Io,jo,Lo,Fo,qo,Wo,Uo,Go,Bo],dependencies:{}}});var qu,Wu,Uu,Gu,Bu,zu=h(()=>{"use strict";c();qu="web.fetch",Wu="Fetch",Uu="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).",Gu="network",Bu={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as li from"cheerio";function Hu(r,e){let t=li.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 w=t(b).first();if(w.length>0&&(a=w.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let l=[];t("p").each((b,w)=>{let T=t(w).text().trim();T.length>50&&l.length<3&&l.push(T)});let p=l.join(`
117
-
118
- `)||a.substring(0,500),m=[];t("h2, h3").each((b,w)=>{let T=t(w).text().trim();T&&T.length>5&&T.length<200&&m.length<10&&m.push(T)});let d=a.split(/\s+/).length,g=a.split(/\s+/);return g.length>2e3&&(a=g.slice(0,2e3).join(" ")+"..."),{title:o,url:e,author:n,publishDate:s,excerpt:p.substring(0,1e3),mainContent:a.substring(0,1e4),keyPoints:m,wordCount:d}}function Ku(r,e){let t=li.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 Ju(r){let e=[];return e.push(`# ${r.title}`),e.push(`URL: ${r.url}`),r.author&&e.push(`Author: ${r.author}`),r.publishDate&&e.push(`Published: ${r.publishDate}`),e.push(`Word Count: ${r.wordCount}`),e.push(""),r.keyPoints.length>0&&(e.push("## Key Points"),r.keyPoints.forEach(t=>{e.push(`- ${t}`)}),e.push("")),e.push("## Excerpt"),e.push(r.excerpt),e.push(""),e.push("## Main Content"),e.push(r.mainContent),e.join(`
119
- `)}function Vu(r){return`# ${r.title}
104
+ }`,variables:{owner:t,name:o,number:n,first:a,after:c,commentsFirst:p}})}),w=await g.text();if(!g.ok)return`HTTP ${g.status} ${g.statusText}
105
+ ${w}`;try{let b=JSON.parse(w);b&&Array.isArray(b.errors)&&b.errors.length>0&&y(`[github.pr.reviewThreads.list] errors=${b.errors.length}`);let T=b?.data?.repository?.pullRequest,k=T?.reviewThreads?.pageInfo??{hasNextPage:!1,endCursor:null},v=T?.reviewThreads?.nodes??[];if(i&&(v=v.filter(x=>x?.isResolved===!1)),m){let x={headRefOid:T?.headRefOid,threads:v,pageInfo:k};return`HTTP 200 OK
106
+ ${JSON.stringify(x)}`}return`HTTP 200 OK
107
+ ${JSON.stringify(v)}`}catch{return`HTTP ${g.status} ${g.statusText}
108
+ ${w}`}}var Oo,Ks=h(()=>{"use strict";l();Hd();Ee();S();be();Oo={name:Wd,displayName:Ud,description:Gd,parameters:zd,category:Bd,execute:_x}});var Kd,Jd,Vd,Qd,Xd,Yd=h(()=>{"use strict";l();Kd="github.pr.reviewThreads.resolve",Jd="Resolve Review Thread",Vd=["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",Xd={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 Rx(r,e){let t=String(r.threadId),o=await B(r.repo,r.token,e?.githubTokenStore,e?.config?.credentials);y(`[github.pr.reviewThreads.resolve] threadId=${t}`);let s=await fetch("https://api.github.com/graphql",{method:"POST",headers:V(o,{"Content-Type":"application/json"}),body:JSON.stringify({query:"mutation($id:ID!){ resolveReviewThread(input:{threadId:$id}) { thread { id isResolved } } }",variables:{id:t}})}),i=await s.text();if(s.ok)try{if(JSON.parse(i).errors?.find(p=>p.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 ${s.status} ${s.statusText}
109
+ ${i}`}var Io,Js=h(()=>{"use strict";l();Yd();Ee();S();be();Io={name:Kd,displayName:Jd,description:Vd,parameters:Xd,category:Qd,execute:Rx}});var Zd,eu,tu,ou,nu,ru=h(()=>{"use strict";l();Zd="github.pr.reviewComments.reply",eu="Reply to Review Comment",tu="Reply within an existing PR review thread to maintain continuity.",ou="github",nu={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 $x(r,e){let t=String(r.repo),o=Number(r.number),n=Number(r.inReplyTo),s=String(r.body),i=await B(t,r.token,e?.githubTokenStore,e?.config?.credentials),a=`https://api.github.com/repos/${t}/pulls/${o}/comments/${n}/replies`;y(`[github.pr.reviewComments.reply] repo=${t} inReplyTo=${n}`);let c=await fetch(a,{method:"POST",headers:V(i,{"Content-Type":"application/json"}),body:JSON.stringify({body:s})}),p=await c.text();return`HTTP ${c.status} ${c.statusText}
110
+ ${p}`}var Lo,Vs=h(()=>{"use strict";l();ru();S();Ee();be();Lo={name:Zd,displayName:eu,description:tu,parameters:nu,category:ou,execute:$x}});var su,iu,au,lu,cu,pu=h(()=>{"use strict";l();su="github.pr.diff.get",iu="Get PR Diff",au="Fetch the unified diff for a pull request (text/patch).",lu="github",cu={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of diff to return; if exceeded, result is truncated with a footer."}},required:["repo","number"]}});import{Buffer as Qs}from"buffer";async function Ex(r,e){let t=String(r.repo),o=Number(r.number),n=await B(t,r.token,e?.githubTokenStore,e?.config?.credentials),s=r.maxBytes?Number(r.maxBytes):void 0,i=`https://api.github.com/repos/${t}/pulls/${o}`;y(`[github.pr.diff.get] repo=${t} pr=${o}`);let a=await fetch(i,{method:"GET",headers:V(n,{Accept:"application/vnd.github.v3.diff"})}),c=await a.text();if(s&&Qs.byteLength(c,"utf8")>s){let p=Qs.from(c,"utf8").subarray(0,s).toString("utf8"),m=`
111
+ \u2026 [truncated, ${s} of ${Qs.byteLength(c,"utf8")} bytes]`;return`HTTP ${a.status} ${a.statusText}
112
+ ${p}${m}`}return`HTTP ${a.status} ${a.statusText}
113
+ ${c}`}var jo,Xs=h(()=>{"use strict";l();pu();Ee();S();be();jo={name:su,displayName:iu,description:au,parameters:cu,category:lu,execute:Ex}});var mu,du,uu,fu,gu,hu=h(()=>{"use strict";l();mu="github.pr.files.list",du="List PR Files",uu="List files changed in a PR with positions metadata.",fu="github",gu={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 Dx(r,e){let t=String(r.repo),o=Number(r.number),n=await B(t,r.token,e?.githubTokenStore,e?.config?.credentials),s=r.perPage?Number(r.perPage):void 0,i=r.page?Number(r.page):void 0,a=new URLSearchParams;s&&a.set("per_page",String(s)),i&&a.set("page",String(i));let c=`https://api.github.com/repos/${t}/pulls/${o}/files${a.toString()?`?${a.toString()}`:""}`;y(`[github.pr.files.list] repo=${t} pr=${o} perPage=${s??""} page=${i??""}`);let p=await fetch(c,{method:"GET",headers:V(n)}),m=await p.text();return`HTTP ${p.status} ${p.statusText}
114
+ ${m}`}var Fo,Ys=h(()=>{"use strict";l();hu();Ee();S();be();Fo={name:mu,displayName:du,description:uu,parameters:gu,category:fu,execute:Dx}});var yu,bu,wu,Tu,xu,vu=h(()=>{"use strict";l();yu="github.pr.reviews.submit",bu="Submit PR Review",wu="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",Tu="github",xu={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 Mx(r,e){let t=String(r.repo),o=Number(r.number),n=String(r.event),s=r.body?String(r.body):void 0,i=Array.isArray(r.comments)?r.comments:void 0,a=await B(t,r.token,e?.githubTokenStore,e?.config?.credentials),c=`https://api.github.com/repos/${t}/pulls/${o}/reviews`;y(`[github.pr.reviews.submit] repo=${t} pr=${o} event=${n} comments=${i?.length??0}`);let p={event:n};s&&(p.body=s),i&&i.length>0&&(p.comments=i);let m=await fetch(c,{method:"POST",headers:V(a,{"Content-Type":"application/json"}),body:JSON.stringify(p)}),d=await m.text();return`HTTP ${m.status} ${m.statusText}
115
+ ${d}`}var qo,Zs=h(()=>{"use strict";l();vu();Ee();S();be();qo={name:yu,displayName:bu,description:wu,parameters:xu,category:Tu,execute:Mx}});var Cu,ku,Su,Pu,_u,Ru=h(()=>{"use strict";l();Cu="github.issues.comments.create",ku="Create Issue/PR Comment",Su="Create a comment on an issue or pull request (conversation tab).",Pu="github",_u={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 Ax(r,e){let t=String(r.repo),o=Number(r.number),n=String(r.body),s=await B(t,r.token,e?.githubTokenStore,e?.config?.credentials),i=`https://api.github.com/repos/${t}/issues/${o}/comments`;y(`[github.issues.comments.create] repo=${t} number=${o}`);let a=await fetch(i,{method:"POST",headers:V(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),c=await a.text();return`HTTP ${a.status} ${a.statusText}
116
+ ${c}`}var Wo,ei=h(()=>{"use strict";l();Ru();Ee();S();be();Wo={name:Cu,displayName:ku,description:Su,parameters:_u,category:Pu,execute:Ax}});var Eu={};oe(Eu,{githubContentsGetTextTool:()=>No,githubGraphqlExecuteTool:()=>Ao,githubIssuesCommentsCreateTool:()=>Wo,githubPrDiffGetTool:()=>jo,githubPrFilesListTool:()=>Fo,githubPrReviewCommentsReplyTool:()=>Lo,githubPrReviewThreadsListTool:()=>Oo,githubPrReviewThreadsResolveTool:()=>Io,githubPrReviewsSubmitTool:()=>qo,githubToolsProject:()=>$u});var $u,ti=h(()=>{"use strict";l();zs();Hs();Ks();Js();Vs();Xs();Ys();Zs();ei();zs();Hs();Ks();Js();Vs();Xs();Ys();Zs();ei();$u={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:[Ao,No,Oo,Io,Lo,jo,Fo,qo,Wo],dependencies:{}}});var Du,Mu,Au,Nu,Ou,Iu=h(()=>{"use strict";l();Du="web.fetch",Mu="Fetch",Au="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).",Nu="network",Ou={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as oi from"cheerio";function Lu(r,e){let t=oi.load(r);t("script, style, nav, header, footer, aside, .advertisement, .ad, .sidebar").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||t('meta[property="og:title"]').attr("content")||"Untitled",n=t('meta[name="author"]').attr("content")||t('meta[property="article:author"]').attr("content")||t(".author").first().text().trim()||void 0,s=t('meta[property="article:published_time"]').attr("content")||t("time").first().attr("datetime")||t(".date, .published").first().text().trim()||void 0,i=["article","main",'[role="main"]',".content",".article-content",".post-content","#content"],a="";for(let w of i){let b=t(w).first();if(b.length>0&&(a=b.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let c=[];t("p").each((w,b)=>{let T=t(b).text().trim();T.length>50&&c.length<3&&c.push(T)});let p=c.join(`
117
+
118
+ `)||a.substring(0,500),m=[];t("h2, h3").each((w,b)=>{let T=t(b).text().trim();T&&T.length>5&&T.length<200&&m.length<10&&m.push(T)});let d=a.split(/\s+/).length,g=a.split(/\s+/);return g.length>2e3&&(a=g.slice(0,2e3).join(" ")+"..."),{title:o,url:e,author:n,publishDate:s,excerpt:p.substring(0,1e3),mainContent:a.substring(0,1e4),keyPoints:m,wordCount:d}}function ju(r,e){let t=oi.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 Fu(r){let e=[];return e.push(`# ${r.title}`),e.push(`URL: ${r.url}`),r.author&&e.push(`Author: ${r.author}`),r.publishDate&&e.push(`Published: ${r.publishDate}`),e.push(`Word Count: ${r.wordCount}`),e.push(""),r.keyPoints.length>0&&(e.push("## Key Points"),r.keyPoints.forEach(t=>{e.push(`- ${t}`)}),e.push("")),e.push("## Excerpt"),e.push(r.excerpt),e.push(""),e.push("## Main Content"),e.push(r.mainContent),e.join(`
119
+ `)}function qu(r){return`# ${r.title}
120
120
  URL: ${r.url}
121
121
 
122
- ${r.snippet}`}var Qu=h(()=>{"use strict";c()});async function Ux(r){let e=r.url,t=r.extractionMode||"full",o=r.headers,n=r.timeout||3e4;if(y(`[web.fetch] execute url="${e}" mode=${t} timeout=${n}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let s=new AbortController,i=setTimeout(()=>s.abort(),n),a;try{a=await fetch(e,{method:"GET",headers:o||{},signal:s.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${n}ms`):p}finally{clearTimeout(i)}if(!a.ok)return`HTTP ${a.status} ${a.statusText}
123
- ${await a.text()}`;let l=await a.text();if(t==="structured"){let p=Hu(l,e);return Ju(p)}else if(t==="minimal"){let p=Ku(l,e);return Vu(p)}else return l.length>15e3?l.substring(0,15e3)+`
122
+ ${r.snippet}`}var Wu=h(()=>{"use strict";l()});async function Nx(r){let e=r.url,t=r.extractionMode||"full",o=r.headers,n=r.timeout||3e4;if(y(`[web.fetch] execute url="${e}" mode=${t} timeout=${n}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let s=new AbortController,i=setTimeout(()=>s.abort(),n),a;try{a=await fetch(e,{method:"GET",headers:o||{},signal:s.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${n}ms`):p}finally{clearTimeout(i)}if(!a.ok)return`HTTP ${a.status} ${a.statusText}
123
+ ${await a.text()}`;let c=await a.text();if(t==="structured"){let p=Lu(c,e);return Fu(p)}else if(t==="minimal"){let p=ju(c,e);return qu(p)}else return c.length>15e3?c.substring(0,15e3)+`
124
124
 
125
- [TRUNCATED: showing 15K of ${l.length} total characters]`:l}var zo,ci=h(()=>{"use strict";c();zu();Qu();S();zo={name:qu,displayName:Wu,description:Uu,parameters:Bu,category:Gu,execute:Ux}});var Xu,Yu,Zu,ef,tf,of=h(()=>{"use strict";c();Xu="web.search",Yu="Search",Zu="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.",ef="network",tf={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});import*as Ue from"fs";import*as Un from"path";function Gn(r){let e=rf(r);if(!Ue.existsSync(e))return{};try{let t=Ue.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Ho(r){let e=Gn(r),t=Bx(e.tools||e);return y(JSON.stringify(t??{})),t}function Gx(r,e){let t=rf(e),o={};try{Ue.existsSync(t)&&(o=JSON.parse(Ue.readFileSync(t,"utf-8")))}catch{o={}}o.tools=r,Ue.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function Bx(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??ce.enabled,autoExecute:r.autoExecute??ce.autoExecute,maxToolRounds:r.maxToolRounds??ce.maxToolRounds,toolChoicePolicy:r.toolChoicePolicy??ce.toolChoicePolicy,resultMaxChars:r.resultMaxChars??ce.resultMaxChars,enabledTools:r.enabledTools??ce.enabledTools,enabledToolCategories:r.enabledToolCategories??ce.enabledToolCategories,toolSearch:r.toolSearch??ce.toolSearch,additionalConfigurations:e}}function rf(r){return r?r.endsWith(".json")?Un.resolve(r):Un.resolve(r,nf):Un.resolve(process.cwd(),nf)}var nf,pi=h(()=>{"use strict";c();zt();S();nf="toolpack.config.json"});import*as af from"cheerio";function Kx(r,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=af.load(r),o=[];return t("a.result-link").each((s,i)=>{if(o.length>=e)return;let a=t(i),l=a.text().trim(),p=a.attr("href"),m=a.siblings(".result-snippet").text().trim();m||(m=a.parent().text().replace(l,"").trim()),l&&p&&o.push({title:l,link:p,snippet:m.slice(0,200)})}),o}function Jx(r){if(r)switch(r){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function sf(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 Vx(r){let e=r.query,t=r.max_results||5,o=r.include_answer||!1,n=r.freshness;y(`[web.search] execute query="${e}" max_results=${t} includeAnswer=${o} freshness=${n??"none"}`);let s=`Request timed out after ${r.timeout||3e4}ms`,i=()=>{let d=new AbortController,g=setTimeout(()=>d.abort(),r.timeout||3e4);return{signal:d.signal,clear:()=>clearTimeout(g)}};if(!e)throw new Error("query is required");let a=Ho();if(y(`[web.search] config=${JSON.stringify(a)}`),a.additionalConfigurations?.webSearch?.tavilyApiKey){y("[web.search] using Tavily API");try{let{signal:d,clear:g}=i(),b=Jx(n),w={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:a.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:o,...b&&{days:b}}),signal:d};y(`[web.search] Tavily request=${JSON.stringify(w)}`);let T=await fetch("https://api.tavily.com/search",w).finally(g);if(T.ok){let v=await T.json();if(v.results&&v.results.length>0){let C=v.results.map(x=>({title:x.title,link:x.url,snippet:x.content}));return o&&v.answer?JSON.stringify({answer:v.answer,results:C},null,2):JSON.stringify(C,null,2)}}else pe(`[web.search] Tavily search failed with status ${T.status}`)}catch(d){pe(`[web.search] Tavily search failed, falling back: ${d}`)}}if(a.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:d,clear:g}=i();if(o){let b=sf(n),w=b?`&freshness=${b}`:"",T=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${w}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:d}).finally(g);if(T.ok){let v=await T.json(),C=v.summarizer?.key;if(C&&v.web?.results){let{signal:x,clear:D}=i(),M=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${C}`,{headers:{Accept:"application/json","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:x}).finally(D);if(M.ok){let k=await M.json(),$=v.web.results.slice(0,t).map(R=>({title:R.title,link:R.url,snippet:R.description})),E=k.summary?.map(R=>R.data).join(`
126
- `)||k.title;return JSON.stringify({answer:E,results:$},null,2)}}if(v.web?.results){let x=v.web.results.slice(0,t).map(D=>({title:D.title,link:D.url,snippet:D.description}));return JSON.stringify(x,null,2)}}}else{let b=sf(n),w=b?`&freshness=${b}`:"",T=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${w}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:d}).finally(g);if(T.ok){let v=await T.json();if(v.web?.results&&v.web.results.length>0){let C=v.web.results.slice(0,t).map(x=>({title:x.title,link:x.url,snippet:x.description}));return JSON.stringify(C,null,2)}}}}catch(d){L(`[web.search] Brave search failed, falling back: ${d}`)}let{signal:l,clear:p}=i(),m;try{m=await fetch(zx,{method:"POST",headers:{"User-Agent":Hx,"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(),g=Kx(d,t);if(g.length>0)return JSON.stringify(g,null,2)}return JSON.stringify({error:"search_unavailable",message:`Search failed to find results for "${e}" across all providers.`,suggestion:"Please configure a search provider API key (tavilyApiKey or braveApiKey) in toolpack.config.json under tools.additionalConfigurations.webSearch."})}var zx,Hx,Ko,mi=h(()=>{"use strict";c();of();pi();S();zx="https://lite.duckduckgo.com/lite/",Hx="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";Ko={name:Xu,displayName:Yu,description:Zu,parameters:tf,category:ef,execute:Vx}});var lf,cf,pf,mf,df,uf=h(()=>{"use strict";c();lf="web.scrape",cf="Scrape",pf="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.",mf="network",df={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as hf from"cheerio";async function Yx(r){let e=r.url,t=r.selector,o=r.section,n=r.format||"text",s=r.max_length||6e3,i=r.timeout||3e4;if(y(`[web.scrape] execute url="${e}" format=${n} selector=${t??"none"} section=${o??"none"} timeout=${i}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let a=new AbortController,l=setTimeout(()=>a.abort(),i),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":Qx},signal:a.signal})}catch(w){throw w.name==="AbortError"?new Error(`Request timed out after ${i}ms`):w}finally{clearTimeout(l)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),d=hf.load(m);for(let w of Xx)d(w).remove();if(n==="tables"){let w=[];return d("table").each((T,v)=>{let C=[],x=[];d(v).find("th").each((D,M)=>{x.push(d(M).text().trim())}),d(v).find("tr").each((D,M)=>{let k=x.length>0?{}:[],$=d(M).find("td");$.length>0&&($.each((E,R)=>{let N=d(R).text().trim();x.length>0&&x[E]?k[x[E]]=N:k.push(N)}),C.push(k))}),C.length>0&&w.push({id:`Table ${T+1}`,headers:x.length>0?x:void 0,rows:C})}),w.length===0?`No tables found on ${e}`:JSON.stringify(w,null,2)}let g="";if(o){let w=o.toLowerCase(),T=null,v=0;if(d("h1, h2, h3, h4, h5, h6").each((C,x)=>{if(d(x).text().toLowerCase().includes(w))return T=x,v=parseInt(x.tagName.charAt(1)),!1}),T){let C=d(T),x=[],D=C.next();for(;D.length>0;){let M=D.prop("tagName")?.toLowerCase();if(M&&/^h[1-6]$/.test(M)&&parseInt(M.charAt(1))<=v)break;let k=D.text().trim();k&&x.push(k),D=D.next()}x.length>0?(g=x.join(`
125
+ [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var Uo,ni=h(()=>{"use strict";l();Iu();Wu();S();Uo={name:Du,displayName:Mu,description:Au,parameters:Ou,category:Nu,execute:Nx}});var Uu,Gu,Bu,zu,Hu,Ku=h(()=>{"use strict";l();Uu="web.search",Gu="Search",Bu="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.",zu="network",Hu={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});import*as Vu from"cheerio";function Lx(r,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=Vu.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 jx(r){if(r)switch(r){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function Ju(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 Fx(r,e){let t=r.query,o=r.max_results||5,n=r.include_answer||!1,s=r.freshness;y(`[web.search] execute query="${t}" max_results=${o} includeAnswer=${n} freshness=${s??"none"}`);let i=`Request timed out after ${r.timeout||3e4}ms`,a=()=>{let w=new AbortController,b=setTimeout(()=>w.abort(),r.timeout||3e4);return{signal:w.signal,clear:()=>clearTimeout(b)}};if(!t)throw new Error("query is required");let c=e?.config?.webSearch?.tavilyApiKey??process.env.TOOLPACK_TAVILY_API_KEY,p=e?.config?.webSearch?.braveApiKey??process.env.TOOLPACK_BRAVE_API_KEY;if(c){y("[web.search] using Tavily API");try{let{signal:w,clear:b}=a(),T=jx(s),k={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:c,query:t,max_results:o,include_answer:n,...T&&{days:T}}),signal:w};y(`[web.search] Tavily request=${JSON.stringify(k)}`);let v=await fetch("https://api.tavily.com/search",k).finally(b);if(v.ok){let x=await v.json();if(x.results&&x.results.length>0){let C=x.results.map(_=>({title:_.title,link:_.url,snippet:_.content}));return n&&x.answer?JSON.stringify({answer:x.answer,results:C},null,2):JSON.stringify(C,null,2)}}else me(`[web.search] Tavily search failed with status ${v.status}`)}catch(w){me(`[web.search] Tavily search failed, falling back: ${w}`)}}if(p)try{let{signal:w,clear:b}=a();if(n){let T=Ju(s),k=T?`&freshness=${T}`:"",v=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(t)}&count=${Math.min(o,20)}&summary=1${k}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":p},signal:w}).finally(b);if(v.ok){let x=await v.json(),C=x.summarizer?.key;if(C&&x.web?.results){let{signal:_,clear:E}=a(),$=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${C}`,{headers:{Accept:"application/json","X-Subscription-Token":p},signal:_}).finally(E);if($.ok){let te=await $.json(),F=x.web.results.slice(0,o).map(q=>({title:q.title,link:q.url,snippet:q.description})),G=te.summary?.map(q=>q.data).join(`
126
+ `)||te.title;return JSON.stringify({answer:G,results:F},null,2)}}if(x.web?.results){let _=x.web.results.slice(0,o).map(E=>({title:E.title,link:E.url,snippet:E.description}));return JSON.stringify(_,null,2)}}}else{let T=Ju(s),k=T?`&freshness=${T}`:"",v=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(t)}&count=${Math.min(o,20)}${k}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":p},signal:w}).finally(b);if(v.ok){let x=await v.json();if(x.web?.results&&x.web.results.length>0){let C=x.web.results.slice(0,o).map(_=>({title:_.title,link:_.url,snippet:_.description}));return JSON.stringify(C,null,2)}}}}catch(w){O(`[web.search] Brave search failed, falling back: ${w}`)}let{signal:m,clear:d}=a(),g;try{g=await fetch(Ox,{method:"POST",headers:{"User-Agent":Ix,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:t}).toString(),signal:m})}catch(w){throw w.name==="AbortError"?new Error(i):w}finally{d()}if(g.ok){let w=await g.text(),b=Lx(w,o);if(b.length>0)return JSON.stringify(b,null,2)}return JSON.stringify({error:"search_unavailable",message:`Search failed to find results for "${t}" across all providers.`,suggestion:"Please configure a search provider API key (tavilyApiKey or braveApiKey) in toolpack.config.json under tools.additionalConfigurations.webSearch."})}var Ox,Ix,Go,ri=h(()=>{"use strict";l();Ku();S();Ox="https://lite.duckduckgo.com/lite/",Ix="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";Go={name:Uu,displayName:Gu,description:Bu,parameters:Hu,category:zu,execute:Fx}});var Qu,Xu,Yu,Zu,ef,tf=h(()=>{"use strict";l();Qu="web.scrape",Xu="Scrape",Yu="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.",Zu="network",ef={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as rf from"cheerio";async function Ux(r){let e=r.url,t=r.selector,o=r.section,n=r.format||"text",s=r.max_length||6e3,i=r.timeout||3e4;if(y(`[web.scrape] execute url="${e}" format=${n} selector=${t??"none"} section=${o??"none"} timeout=${i}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let a=new AbortController,c=setTimeout(()=>a.abort(),i),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":qx},signal:a.signal})}catch(b){throw b.name==="AbortError"?new Error(`Request timed out after ${i}ms`):b}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),d=rf.load(m);for(let b of Wx)d(b).remove();if(n==="tables"){let b=[];return d("table").each((T,k)=>{let v=[],x=[];d(k).find("th").each((C,_)=>{x.push(d(_).text().trim())}),d(k).find("tr").each((C,_)=>{let E=x.length>0?{}:[],$=d(_).find("td");$.length>0&&($.each((te,F)=>{let G=d(F).text().trim();x.length>0&&x[te]?E[x[te]]=G:E.push(G)}),v.push(E))}),v.length>0&&b.push({id:`Table ${T+1}`,headers:x.length>0?x:void 0,rows:v})}),b.length===0?`No tables found on ${e}`:JSON.stringify(b,null,2)}let g="";if(o){let b=o.toLowerCase(),T=null,k=0;if(d("h1, h2, h3, h4, h5, h6").each((v,x)=>{if(d(x).text().toLowerCase().includes(b))return T=x,k=parseInt(x.tagName.charAt(1)),!1}),T){let v=d(T),x=[],C=v.next();for(;C.length>0;){let _=C.prop("tagName")?.toLowerCase();if(_&&/^h[1-6]$/.test(_)&&parseInt(_.charAt(1))<=k)break;let E=C.text().trim();E&&x.push(E),C=C.next()}x.length>0?(g=x.join(`
127
127
 
128
128
  `).replace(/\s+/g," ").trim(),g=`[Section: "${o}"]
129
129
 
@@ -131,32 +131,32 @@ ${g}`):g=`[Note: Found heading "${o}" but no content below it. Falling back to f
131
131
 
132
132
  `}else g=`[Note: Section "${o}" not found. Falling back to full page.]
133
133
 
134
- `}if(!g||g.includes("Falling back to full page"))if(g&&g.includes("Falling back to full page")&&(g=""),t){let w=d(t);if(w.length>0)g=w.text().replace(/\s+/g," ").trim();else{for(let T of ff){let v=d(T);if(v.length>0){let C=v.text().replace(/\s+/g," ").trim();if(C.length>gf){g=C;break}}}if(g)g=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
134
+ `}if(!g||g.includes("Falling back to full page"))if(g&&g.includes("Falling back to full page")&&(g=""),t){let b=d(t);if(b.length>0)g=b.text().replace(/\s+/g," ").trim();else{for(let T of of){let k=d(T);if(k.length>0){let v=k.text().replace(/\s+/g," ").trim();if(v.length>nf){g=v;break}}}if(g)g=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
135
135
 
136
- ${g}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let w of ff){let T=d(w);if(T.length>0){let v=T.text().replace(/\s+/g," ").trim();if(v.length>gf){g=v;break}}}if(g||(g=d("body").text().replace(/\s+/g," ").trim(),g&&(g=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
136
+ ${g}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let b of of){let T=d(b);if(T.length>0){let k=T.text().replace(/\s+/g," ").trim();if(k.length>nf){g=k;break}}}if(g||(g=d("body").text().replace(/\s+/g," ").trim(),g&&(g=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
137
137
 
138
- ${g}`)),!g)return`Could not extract any content from ${e}`;if(g.length>s){let w=g.substring(0,s);return`[Warning: Content exceeds ${s} chars (actual: ${g.length} chars). Showing first ${s} chars only.]
138
+ ${g}`)),!g)return`Could not extract any content from ${e}`;if(g.length>s){let b=g.substring(0,s);return`[Warning: Content exceeds ${s} chars (actual: ${g.length} chars). Showing first ${s} chars only.]
139
139
 
140
140
  RECOMMENDATION: Use web.map to see page structure, then use web.scrape with section parameter to extract specific sections.
141
141
 
142
142
  Page content from ${e}:
143
143
 
144
- ${w}
144
+ ${b}
145
145
 
146
146
  ... [Content truncated. ${g.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
147
147
 
148
- ${g}`}var Qx,Xx,ff,gf,Jo,di=h(()=>{"use strict";c();uf();S();Qx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Xx=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],ff=["article","main",".content","#content",'[role="main"]',"body"],gf=200;Jo={name:lf,displayName:cf,description:pf,parameters:df,category:mf,execute:Yx}});var yf,bf,wf,Tf,xf,vf=h(()=>{"use strict";c();yf="web.extract_links",bf="Extract Links",wf="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Tf="network",xf={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Cf from"cheerio";async function ev(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":Zx},signal:n.signal})}catch(d){throw d.name==="AbortError"?new Error(`Request timed out after ${o}ms`):d}finally{clearTimeout(s)}if(!i.ok)throw new Error(`Failed to fetch ${e}: HTTP ${i.status} ${i.statusText}`);let a=await i.text(),l=Cf.load(a),p=new URL(e),m=[];return l("a[href]").each((d,g)=>{let b=l(g),w=b.attr("href");if(!w)return;let T;try{T=new URL(w,e).toString()}catch{return}if(T.startsWith("javascript:")||T.startsWith("mailto:")||T.startsWith("tel:"))return;let v=b.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(T).hostname!==p.hostname)return}catch{return}else if(!T.includes(t))return}m.push({text:v,url:T})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var Zx,Vo,ui=h(()=>{"use strict";c();vf();Zx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Vo={name:yf,displayName:bf,description:wf,parameters:xf,category:Tf,execute:ev}});var kf,Sf,Pf,_f,Rf,$f=h(()=>{"use strict";c();kf="web.map",Sf="Map",Pf="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.",_f="network",Rf={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Ef from"cheerio";async function ov(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":tv},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=Ef.load(i),l=[];if(a("h1, h2, h3, h4, h5, h6").each((m,d)=>{let g=d.tagName.toLowerCase(),b=parseInt(g.charAt(1)),w=a(d).text().trim();w&&l.push({level:b,text:w})}),l.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
148
+ ${g}`}var qx,Wx,of,nf,Bo,si=h(()=>{"use strict";l();tf();S();qx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Wx=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],of=["article","main",".content","#content",'[role="main"]',"body"],nf=200;Bo={name:Qu,displayName:Xu,description:Yu,parameters:ef,category:Zu,execute:Ux}});var sf,af,lf,cf,pf,mf=h(()=>{"use strict";l();sf="web.extract_links",af="Extract Links",lf="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",cf="network",pf={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as df from"cheerio";async function Bx(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":Gx},signal:n.signal})}catch(d){throw d.name==="AbortError"?new Error(`Request timed out after ${o}ms`):d}finally{clearTimeout(s)}if(!i.ok)throw new Error(`Failed to fetch ${e}: HTTP ${i.status} ${i.statusText}`);let a=await i.text(),c=df.load(a),p=new URL(e),m=[];return c("a[href]").each((d,g)=>{let w=c(g),b=w.attr("href");if(!b)return;let T;try{T=new URL(b,e).toString()}catch{return}if(T.startsWith("javascript:")||T.startsWith("mailto:")||T.startsWith("tel:"))return;let k=w.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(T).hostname!==p.hostname)return}catch{return}else if(!T.includes(t))return}m.push({text:k,url:T})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var Gx,zo,ii=h(()=>{"use strict";l();mf();Gx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";zo={name:sf,displayName:af,description:lf,parameters:pf,category:cf,execute:Bx}});var uf,ff,gf,hf,yf,bf=h(()=>{"use strict";l();uf="web.map",ff="Map",gf="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.",hf="network",yf={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as wf from"cheerio";async function Hx(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":zx},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=wf.load(i),c=[];if(a("h1, h2, h3, h4, h5, h6").each((m,d)=>{let g=d.tagName.toLowerCase(),w=parseInt(g.charAt(1)),b=a(d).text().trim();b&&c.push({level:w,text:b})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
149
149
 
150
- `;for(let m of l){let d=" ".repeat(m.level-1);p+=`${d}${"#".repeat(m.level)} ${m.text}
151
- `}return p}var tv,Qo,fi=h(()=>{"use strict";c();$f();tv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Qo={name:kf,displayName:Sf,description:Pf,parameters:Rf,category:_f,execute:ov}});var Df,Mf,Af,Nf,Of,If=h(()=>{"use strict";c();Df="web.metadata",Mf="Extract Metadata",Af="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Nf="network",Of={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as jf from"cheerio";async function rv(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":nv},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=jf.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:",""),g=a(m).attr("content");d&&g&&(l.openGraph[d]=g)}),a('meta[name^="twitter:"]').each((p,m)=>{let d=a(m).attr("name")?.replace("twitter:",""),g=a(m).attr("content");d&&g&&(l.twitter[d]=g)}),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 nv,Xo,gi=h(()=>{"use strict";c();If();nv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Xo={name:Df,displayName:Mf,description:Af,parameters:Of,category:Nf,execute:rv}});var Lf,Ff,qf,Wf,Uf,Gf=h(()=>{"use strict";c();Lf="web.sitemap",Ff="Extract Sitemap",qf="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Wf="network",Uf={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Bf from"cheerio";async function hi(r,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(r,{method:"GET",headers:{"User-Agent":sv},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function iv(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 hi(n,o),!i.ok&&s&&(n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await hi(n,o))}catch(p){if(s)n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await hi(n,o);else throw p}if(!i||!i.ok)throw new Error(`Failed to fetch sitemap or robots.txt from ${e}`);let a=await i.text(),l=[];if(n.endsWith(".xml")||a.trim().startsWith("<")){let p=Bf.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((g,b)=>{l.length>=t||l.push({loc:p(b).text()})}),JSON.stringify({type:"sitemapindex",urls:l},null,2);p("urlset > url").each((g,b)=>{if(l.length>=t)return;let w=p(b);l.push({loc:w.children("loc").text(),lastmod:w.children("lastmod").text()||void 0,priority:w.children("priority").text()||void 0})})}else{let p=a.split(`
152
- `);for(let m of p){if(l.length>=t)break;let d=m.trim();if(d.toLowerCase().startsWith("sitemap:"))l.push({loc:d.substring(8).trim()});else if(d.toLowerCase().startsWith("allow:")){let g=d.substring(6).trim();l.push({loc:new URL(g,n).toString()})}}}return JSON.stringify(l,null,2)}var sv,Yo,yi=h(()=>{"use strict";c();Gf();sv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Yo={name:Lf,displayName:Ff,description:qf,parameters:Uf,category:Wf,execute:iv}});var zf,Hf,Kf,Jf,Vf,Qf=h(()=>{"use strict";c();zf="web.feed",Hf="Extract Feed",Kf="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",Jf="network",Vf={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 Xf(){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 Yf=h(()=>{"use strict";c()});async function av(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 Xf();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 Zo,bi=h(()=>{"use strict";c();Qf();Yf();Zo={name:zf,displayName:Hf,description:Kf,parameters:Vf,category:Jf,execute:av}});var Zf,eg,tg,og,ng,rg=h(()=>{"use strict";c();Zf="web.screenshot",eg="Screenshot",tg="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",og="network",ng={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 sg(){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 ig=h(()=>{"use strict";c()});async function cv(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 sg()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(lv),await a.setViewport({width:o?.width||1280,height:o?.height||800}),await a.goto(e,{waitUntil:"networkidle2",timeout:n}),t==="png"){let l=await a.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(l)?p=l.toString("base64"):p=Buffer.from(l).toString("base64"),`data:image/png;base64,${p}`}else return await a.content()}finally{await i.close()}}var lv,en,wi=h(()=>{"use strict";c();rg();ig();lv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";en={name:Zf,displayName:eg,description:tg,parameters:ng,category:og,execute:cv}});var lg={};ne(lg,{webExtractLinksTool:()=>Vo,webFeedTool:()=>Zo,webFetchTool:()=>zo,webMapTool:()=>Qo,webMetadataTool:()=>Xo,webScrapeTool:()=>Jo,webScreenshotTool:()=>en,webSearchTool:()=>Ko,webSitemapTool:()=>Yo,webToolsProject:()=>ag});var ag,Ti=h(()=>{"use strict";c();ci();mi();di();ui();fi();gi();yi();bi();wi();ci();mi();di();ui();fi();gi();yi();bi();wi();ag={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:[zo,Ko,Jo,Vo,Qo,Xo,Yo,Zo,en],dependencies:{cheerio:"^1.0.0-rc.12"}}});var cg,pg,mg,dg,ug,fg=h(()=>{"use strict";c();cg="coding.find_symbol",pg="Find Symbol",mg="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",dg="coding",ug={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});import{extname as pv}from"path";function Bn(r){let e=pv(r).toLowerCase();return mv[e]||"unknown"}var mv,xi=h(()=>{"use strict";c();mv={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});import*as it from"web-tree-sitter";import*as Ae from"fs";import*as Ge from"path";import*as hg from"os";var gg,vi,dv,zn,yg=h(()=>{"use strict";c();gg=it.default||it.Parser||it,vi=Ge.join(hg.homedir(),".toolpack-sdk","grammars"),dv=Ge.resolve(u,"../../grammars"),zn=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await gg.init({locateFile(e,t){return Ge.join(u,"../../../../../../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(it.Language||gg.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Ge.resolve(u,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(Ae.existsSync(o))return o;let n=Ge.join(dv,t);if(Ae.existsSync(n))return n;let s=Ge.join(vi,t);return Ae.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){Ae.existsSync(vi)||Ae.mkdirSync(vi,{recursive:!0});let o=`https://unpkg.com/tree-sitter-wasms@latest/out/tree-sitter-${e}.wasm`,n=await fetch(o);if(!n.ok)throw new Error(`Failed to download grammar for ${e}: ${n.statusText}`);let s=await n.arrayBuffer(),i=Buffer.from(s);Ae.writeFileSync(t,i)}}});import*as tn from"web-tree-sitter";import*as bg from"fs";import*as wg from"crypto";var uv,Hn,Tg=h(()=>{"use strict";c();xi();yg();uv=tn.default||tn.Parser||tn,Hn=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new zn}hash(e){return wg.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=Bn(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 uv),this.parser.setLanguage(a);let l;return s?(s.tree&&s.tree.delete(),l=this.parser.parse(o)):l=this.parser.parse(o),this.treeCache.set(e,{tree:l,language:i,contentHash:n,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:l,language:i,grammar:a}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[o,n]of this.treeCache.entries())n.lastAccessed<t&&(t=n.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});import{parse as fv}from"@babel/parser";import*as Ci from"@babel/traverse";var Ee,Kn,xg=h(()=>{"use strict";c();Ee=Ci.default||Ci,Kn=class{parseCode(e){return fv(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;Ee(s,{FunctionDeclaration(a){a.node.id?.name===t&&(!o||o==="function")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(a){a.node.id?.name===t&&(!o||o==="class")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(a){if(a.node.id.type==="Identifier"&&a.node.id.name===t){let l=a.parent,p=l.type==="VariableDeclaration"?l.kind:"variable";(!o||o===p||o==="variable")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(a){a.node.id.name===t&&(!o||o==="interface")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(a){a.node.id.name===t&&(!o||o==="type")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return n}async getSymbols(e,t){let o=[];try{let n=this.parseCode(e.content);Ee(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);Ee(o,{ImportDeclaration(n){let s=n.node.source.value,i=[],a="side-effect";for(let l of n.node.specifiers)if(l.type==="ImportDefaultSpecifier")i.push(l.local.name),a="default";else if(l.type==="ImportNamespaceSpecifier")i.push(`* as ${l.local.name}`),a="namespace";else if(l.type==="ImportSpecifier"){let p=l.imported.type==="Identifier"?l.imported.name:l.imported.value,m=l.local.name;i.push(p===m?p:`${p} as ${m}`),a="named"}t.push({source:s,imports:i,line:n.node.loc?.start.line||0,type:a})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return t}async findReferences(e,t,o){let n=[];try{let s=e.content,i=s.split(`
153
- `),a=this.parseCode(s);Ee(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,g=i[m-1]||"";n.push({file:e.filePath,line:m,column:d,context:g.trim(),isDeclaration:p})}}}})}catch{}return n}async getSymbolAtPosition(e,t,o){try{let n=this.parseCode(e.content),s=null;return Ee(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 Ee(o,{FunctionDeclaration(i){i.node.id?.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t},i.stop())},ClassDeclaration(i){i.node.id?.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t},i.stop())},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let a=i.parent,l=a.type==="VariableDeclaration"?a.kind:"variable";s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:l,name:t},i.stop()}},TSInterfaceDeclaration(i){i.node.id.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t},i.stop())},TSTypeAliasDeclaration(i){i.node.id.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t},i.stop())}}),s}catch{return null}}async getDiagnostics(e){try{return this.parseCode(e.content),[]}catch(t){return[{message:t.message,line:t.loc?.line||0,column:t.loc?.column||0,severity:"error"}]}}async getExports(e){let t=[];try{let o=this.parseCode(e.content);Ee(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(`
154
- `),l=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(l,p).join(`
150
+ `;for(let m of c){let d=" ".repeat(m.level-1);p+=`${d}${"#".repeat(m.level)} ${m.text}
151
+ `}return p}var zx,Ho,ai=h(()=>{"use strict";l();bf();zx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Ho={name:uf,displayName:ff,description:gf,parameters:yf,category:hf,execute:Hx}});var Tf,xf,vf,Cf,kf,Sf=h(()=>{"use strict";l();Tf="web.metadata",xf="Extract Metadata",vf="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Cf="network",kf={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Pf from"cheerio";async function Jx(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":Kx},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=Pf.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 d=a(m).attr("property")?.replace("og:",""),g=a(m).attr("content");d&&g&&(c.openGraph[d]=g)}),a('meta[name^="twitter:"]').each((p,m)=>{let d=a(m).attr("name")?.replace("twitter:",""),g=a(m).attr("content");d&&g&&(c.twitter[d]=g)}),a('script[type="application/ld+json"]').each((p,m)=>{let d=a(m).html();if(d)try{c.jsonLd.push(JSON.parse(d))}catch{}}),JSON.stringify(c,null,2)}var Kx,Ko,li=h(()=>{"use strict";l();Sf();Kx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Ko={name:Tf,displayName:xf,description:vf,parameters:kf,category:Cf,execute:Jx}});var _f,Rf,$f,Ef,Df,Mf=h(()=>{"use strict";l();_f="web.sitemap",Rf="Extract Sitemap",$f="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Ef="network",Df={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Af from"cheerio";async function ci(r,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(r,{method:"GET",headers:{"User-Agent":Vx},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function Qx(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 ci(n,o),!i.ok&&s&&(n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ci(n,o))}catch(p){if(s)n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ci(n,o);else throw p}if(!i||!i.ok)throw new Error(`Failed to fetch sitemap or robots.txt from ${e}`);let a=await i.text(),c=[];if(n.endsWith(".xml")||a.trim().startsWith("<")){let p=Af.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((g,w)=>{c.length>=t||c.push({loc:p(w).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((g,w)=>{if(c.length>=t)return;let b=p(w);c.push({loc:b.children("loc").text(),lastmod:b.children("lastmod").text()||void 0,priority:b.children("priority").text()||void 0})})}else{let p=a.split(`
152
+ `);for(let m of p){if(c.length>=t)break;let d=m.trim();if(d.toLowerCase().startsWith("sitemap:"))c.push({loc:d.substring(8).trim()});else if(d.toLowerCase().startsWith("allow:")){let g=d.substring(6).trim();c.push({loc:new URL(g,n).toString()})}}}return JSON.stringify(c,null,2)}var Vx,Jo,pi=h(()=>{"use strict";l();Mf();Vx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Jo={name:_f,displayName:Rf,description:$f,parameters:Df,category:Ef,execute:Qx}});var Nf,Of,If,Lf,jf,Ff=h(()=>{"use strict";l();Nf="web.feed",Of="Extract Feed",If="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",Lf="network",jf={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 qf(){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 Wf=h(()=>{"use strict";l()});async function Xx(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 qf();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 Vo,mi=h(()=>{"use strict";l();Ff();Wf();Vo={name:Nf,displayName:Of,description:If,parameters:jf,category:Lf,execute:Xx}});var Uf,Gf,Bf,zf,Hf,Kf=h(()=>{"use strict";l();Uf="web.screenshot",Gf="Screenshot",Bf="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",zf="network",Hf={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 Jf(){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 Vf=h(()=>{"use strict";l()});async function Zx(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 Jf()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(Yx),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 Yx,Qo,di=h(()=>{"use strict";l();Kf();Vf();Yx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Qo={name:Uf,displayName:Gf,description:Bf,parameters:Hf,category:zf,execute:Zx}});var Xf={};oe(Xf,{webExtractLinksTool:()=>zo,webFeedTool:()=>Vo,webFetchTool:()=>Uo,webMapTool:()=>Ho,webMetadataTool:()=>Ko,webScrapeTool:()=>Bo,webScreenshotTool:()=>Qo,webSearchTool:()=>Go,webSitemapTool:()=>Jo,webToolsProject:()=>Qf});var Qf,ui=h(()=>{"use strict";l();ni();ri();si();ii();ai();li();pi();mi();di();ni();ri();si();ii();ai();li();pi();mi();di();Qf={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:[Uo,Go,Bo,zo,Ho,Ko,Jo,Vo,Qo],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Yf,Zf,eg,tg,og,ng=h(()=>{"use strict";l();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"]}});import{extname as ev}from"path";function Ln(r){let e=ev(r).toLowerCase();return tv[e]||"unknown"}var tv,fi=h(()=>{"use strict";l();tv={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});import*as it from"web-tree-sitter";import*as Ne from"fs";import*as Ge from"path";import*as sg from"os";var rg,gi,ov,jn,ig=h(()=>{"use strict";l();rg=it.default||it.Parser||it,gi=Ge.join(sg.homedir(),".toolpack-sdk","grammars"),ov=Ge.resolve(u,"../../grammars"),jn=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await rg.init({locateFile(e,t){return Ge.join(u,"../../../../../../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(it.Language||rg.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Ge.resolve(u,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(Ne.existsSync(o))return o;let n=Ge.join(ov,t);if(Ne.existsSync(n))return n;let s=Ge.join(gi,t);return Ne.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){Ne.existsSync(gi)||Ne.mkdirSync(gi,{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)}}});import*as Xo from"web-tree-sitter";import*as ag from"fs";import*as lg from"crypto";var nv,Fn,cg=h(()=>{"use strict";l();fi();ig();nv=Xo.default||Xo.Parser||Xo,Fn=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new jn}hash(e){return lg.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:ag.readFileSync(e,"utf-8"),n=this.hash(o),s=this.treeCache.get(e),i=Ln(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 nv),this.parser.setLanguage(a);let c;return s?(s.tree&&s.tree.delete(),c=this.parser.parse(o)):c=this.parser.parse(o),this.treeCache.set(e,{tree:c,language:i,contentHash:n,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:c,language:i,grammar:a}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[o,n]of this.treeCache.entries())n.lastAccessed<t&&(t=n.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});import{parse as rv}from"@babel/parser";import*as hi from"@babel/traverse";var De,qn,pg=h(()=>{"use strict";l();De=hi.default||hi,qn=class{parseCode(e){return rv(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;De(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);De(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);De(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(`
153
+ `),a=this.parseCode(s);De(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,d=c.node.loc?.start.column||0,g=i[m-1]||"";n.push({file:e.filePath,line:m,column:d,context:g.trim(),isDeclaration:p})}}}})}catch{}return n}async getSymbolAtPosition(e,t,o){try{let n=this.parseCode(e.content),s=null;return De(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 De(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);De(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(`
154
+ `),c=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(c,p).join(`
155
155
  `),d=`
156
156
  function ${i}() {
157
157
  ${m}
158
158
  }
159
- `,g=`${i}();`;return{newFunction:d,replacementCall:g}}async getCallHierarchy(e,t,o){try{let n=this.parseCode(e.content),s=e.filePath,i=null,a="",l=0,p=0;if(Ee(n,{Function(w){let T=w.node.loc;T&&T.start.line<=t&&T.end&&T.end.line>=t&&(i=w,l=T.start.line,p=T.start.column,w.node.type==="FunctionDeclaration"&&w.node.id?a=w.node.id.name:w.parent.type==="VariableDeclarator"&&w.parent.id.type==="Identifier"?a=w.parent.id.name:w.parent.type==="ClassMethod"||w.parent.type==="ObjectMethod"?w.parent.key.type==="Identifier"&&(a=w.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let m=[],d=[];Ee(n,{CallExpression(w){let T=w.node.loc;if(!T||T.start.line<l||T.end&&T.end.line>l+1e3)return;let v=!1,C=w;for(;C;){if(C.isFunction()&&C.node.type==="FunctionDeclaration"&&C.node.id?.name===a){v=!0;break}C=C.parentPath}if(!v)return;let x=w.node.callee,D="<unknown>";x.type==="Identifier"?D=x.name:x.type==="MemberExpression"&&x.property.type==="Identifier"&&(D=x.property.name),D!=="<unknown>"&&d.push({file:s,name:D,line:w.node.loc?.start.line||0,column:w.node.loc?.start.column||0})}}),Ee(n,{CallExpression(w){let T=w.node.callee,v=!1;if((T.type==="Identifier"&&T.name===a||T.type==="MemberExpression"&&T.property.type==="Identifier"&&T.property.name===a)&&(v=!0),v){let C="<global>",x=w;for(;x;){if(x.isFunction()){x.node.type==="FunctionDeclaration"&&x.node.id?C=x.node.id.name:x.parent.type==="VariableDeclarator"&&x.parent.id.type==="Identifier"?C=x.parent.id.name:(x.parent.type==="ClassMethod"||x.parent.type==="ObjectMethod")&&x.parent.key.type==="Identifier"&&(C=x.parent.key.name);break}x=x.parentPath}m.push({file:s,name:C,line:w.node.loc?.start.line||0,column:w.node.loc?.start.column||0})}}});let g=[...new Map(m.map(w=>[`${w.name}:${w.line}`,w])).values()],b=[...new Map(d.map(w=>[`${w.name}:${w.line}`,w])).values()];return{file:s,name:a,line:l,column:p,callers:g,callees:b}}catch{return null}}}});function Se(r,e){ki[r]=e}var ki,at=h(()=>{"use strict";c();ki={}});var gv,vg=h(()=>{"use strict";c();at();gv={symbols:`
159
+ `,g=`${i}();`;return{newFunction:d,replacementCall:g}}async getCallHierarchy(e,t,o){try{let n=this.parseCode(e.content),s=e.filePath,i=null,a="",c=0,p=0;if(De(n,{Function(b){let T=b.node.loc;T&&T.start.line<=t&&T.end&&T.end.line>=t&&(i=b,c=T.start.line,p=T.start.column,b.node.type==="FunctionDeclaration"&&b.node.id?a=b.node.id.name:b.parent.type==="VariableDeclarator"&&b.parent.id.type==="Identifier"?a=b.parent.id.name:b.parent.type==="ClassMethod"||b.parent.type==="ObjectMethod"?b.parent.key.type==="Identifier"&&(a=b.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let m=[],d=[];De(n,{CallExpression(b){let T=b.node.loc;if(!T||T.start.line<c||T.end&&T.end.line>c+1e3)return;let k=!1,v=b;for(;v;){if(v.isFunction()&&v.node.type==="FunctionDeclaration"&&v.node.id?.name===a){k=!0;break}v=v.parentPath}if(!k)return;let x=b.node.callee,C="<unknown>";x.type==="Identifier"?C=x.name:x.type==="MemberExpression"&&x.property.type==="Identifier"&&(C=x.property.name),C!=="<unknown>"&&d.push({file:s,name:C,line:b.node.loc?.start.line||0,column:b.node.loc?.start.column||0})}}),De(n,{CallExpression(b){let T=b.node.callee,k=!1;if((T.type==="Identifier"&&T.name===a||T.type==="MemberExpression"&&T.property.type==="Identifier"&&T.property.name===a)&&(k=!0),k){let v="<global>",x=b;for(;x;){if(x.isFunction()){x.node.type==="FunctionDeclaration"&&x.node.id?v=x.node.id.name:x.parent.type==="VariableDeclarator"&&x.parent.id.type==="Identifier"?v=x.parent.id.name:(x.parent.type==="ClassMethod"||x.parent.type==="ObjectMethod")&&x.parent.key.type==="Identifier"&&(v=x.parent.key.name);break}x=x.parentPath}m.push({file:s,name:v,line:b.node.loc?.start.line||0,column:b.node.loc?.start.column||0})}}});let g=[...new Map(m.map(b=>[`${b.name}:${b.line}`,b])).values()],w=[...new Map(d.map(b=>[`${b.name}:${b.line}`,b])).values()];return{file:s,name:a,line:c,column:p,callers:g,callees:w}}catch{return null}}}});function ke(r,e){yi[r]=e}var yi,at=h(()=>{"use strict";l();yi={}});var sv,mg=h(()=>{"use strict";l();at();sv={symbols:`
160
160
  (function_definition
161
161
  name: (identifier) @name.function) @definition.function
162
162
 
@@ -174,7 +174,7 @@ ${m}
174
174
  name: (dotted_name) @name) @import
175
175
  `,references:`
176
176
  (identifier) @reference
177
- `};Se("python",gv)});var hv,Cg=h(()=>{"use strict";c();at();hv={symbols:`
177
+ `};ke("python",sv)});var iv,dg=h(()=>{"use strict";l();at();iv={symbols:`
178
178
  (function_declaration
179
179
  name: (identifier) @name.function) @definition.function
180
180
 
@@ -202,7 +202,7 @@ ${m}
202
202
  (identifier) @reference
203
203
  (field_identifier) @reference
204
204
  (type_identifier) @reference
205
- `};Se("go",hv)});var yv,kg=h(()=>{"use strict";c();at();yv={symbols:`
205
+ `};ke("go",iv)});var av,ug=h(()=>{"use strict";l();at();av={symbols:`
206
206
  (function_item
207
207
  name: (identifier) @name.function) @definition.function
208
208
 
@@ -224,7 +224,7 @@ ${m}
224
224
  (identifier) @reference
225
225
  (type_identifier) @reference
226
226
  (field_identifier) @reference
227
- `};Se("rust",yv)});var bv,Sg=h(()=>{"use strict";c();at();bv={symbols:`
227
+ `};ke("rust",av)});var lv,fg=h(()=>{"use strict";l();at();lv={symbols:`
228
228
  (method_declaration
229
229
  name: (identifier) @name.method) @definition.method
230
230
 
@@ -245,7 +245,7 @@ ${m}
245
245
  `,references:`
246
246
  (identifier) @reference
247
247
  (type_identifier) @reference
248
- `};Se("java",bv)});var Pg,_g=h(()=>{"use strict";c();at();Pg={symbols:`
248
+ `};ke("java",lv)});var gg,hg=h(()=>{"use strict";l();at();gg={symbols:`
249
249
  (function_definition
250
250
  declarator: (function_declarator
251
251
  declarator: (identifier) @name.function)) @definition.function
@@ -266,23 +266,23 @@ ${m}
266
266
  (identifier) @reference
267
267
  (type_identifier) @reference
268
268
  (field_identifier) @reference
269
- `};Se("cpp",Pg);Se("c",Pg)});var Jn,Rg=h(()=>{"use strict";c();at();vg();Cg();kg();Sg();_g();Jn=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=ki[n];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${n}`);let a=i[t],l=s.query(a);return{tree:o,captures:l.captures(o.rootNode)}}async findSymbols(e,t,o){return(await this.getSymbols(e,o)).filter(s=>s.name===t).map(s=>({file:e.filePath,line:s.line,column:s.column,kind:s.kind,name:s.name}))}async getSymbols(e,t){let{captures:o}=await this.executeQuery(e,"symbols"),n=[];for(let s of o)if(s.name.startsWith("name.")){let i=s.name.split(".")[1];(!t||t===i)&&n.push({name:s.node.text,kind:i,line:s.node.startPosition.row+1,column:s.node.startPosition.column})}return n}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),o=t.filter(s=>s.name==="import").map(s=>s.node),n=[];for(let s of o)n.push({source:s.text,imports:[s.text],line:s.startPosition.row+1,type:"side-effect"});return n}async findReferences(e,t,o){let{captures:n}=await this.executeQuery(e,"references"),s=e.content.split(`
270
- `),i=[];for(let a of n)if(a.node.text===t){let l=a.node.parent?.type.includes("definition")||a.node.parent?.type.includes("declaration");if(!l||o){let p=a.node.startPosition.row+1;i.push({file:e.filePath,line:p,column:a.node.startPosition.column,context:s[p-1].trim(),isDeclaration:!!l})}}return i}async getSymbolAtPosition(e,t,o){let{tree:n}=await this.context.getTree(e.filePath,e.content),s=n.rootNode.descendantForPosition({row:t-1,column:o});return s&&s.type==="identifier"?s.text:null}async getDefinition(e,t){let o=await this.findSymbols(e,t);return o.length>0?o[0]:null}async getDiagnostics(e){let{tree:t}=await this.context.getTree(e.filePath,e.content),o=[];function n(s){if(s.hasError()){s.type==="ERROR"&&o.push({message:`Syntax error at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"});for(let i of s.children)n(i)}else s.isMissing&&s.isMissing()&&o.push({message:`Missing ${s.type} at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"})}return n(t.rootNode),o}async getExports(e){return[]}async getOutline(e){return(await this.getSymbols(e)).map(o=>({name:o.name,kind:o.kind,line:o.line,column:o.column,children:[]}))}async extractFunction(e,t,o,n,s,i){let a=e.content.split(`
271
- `),l=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(l,p).join(`
272
- `),d="",g="",b=e.filePath.split(".").pop()?.toLowerCase();return b==="py"||b==="pyi"?(d=`
269
+ `};ke("cpp",gg);ke("c",gg)});var Wn,yg=h(()=>{"use strict";l();at();mg();dg();ug();fg();hg();Wn=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=yi[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(`
270
+ `),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(`
271
+ `),c=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(c,p).join(`
272
+ `),d="",g="",w=e.filePath.split(".").pop()?.toLowerCase();return w==="py"||w==="pyi"?(d=`
273
273
  def ${i}():
274
274
  ${m.split(`
275
- `).map(w=>" "+w).join(`
275
+ `).map(b=>" "+b).join(`
276
276
  `)}
277
- `,g=`${i}()`):b==="go"?(d=`
277
+ `,g=`${i}()`):w==="go"?(d=`
278
278
  func ${i}() {
279
279
  ${m}
280
280
  }
281
- `,g=`${i}()`):b==="rs"?(d=`
281
+ `,g=`${i}()`):w==="rs"?(d=`
282
282
  fn ${i}() {
283
283
  ${m}
284
284
  }
285
- `,g=`${i}();`):b==="sh"||b==="bash"?(d=`
285
+ `,g=`${i}();`):w==="sh"||w==="bash"?(d=`
286
286
  ${i}() {
287
287
  ${m}
288
288
  }
@@ -290,24 +290,24 @@ ${m}
290
290
  void ${i}() {
291
291
  ${m}
292
292
  }
293
- `,g=`${i}();`),{newFunction:d,replacementCall:g}}async getCallHierarchy(e,t,o){let n=await this.getSymbolAtPosition(e,t,o);if(!n)return null;let i=(await this.findReferences(e,n,!1)).map(a=>({file:a.file,name:a.context.trim()||"<anonymous>",line:a.line,column:a.column}));return{file:e.filePath,name:n,line:t,column:o,callers:i,callees:[]}}}});var Vn,$g=h(()=>{"use strict";c();xi();xg();Rg();Vn=class{constructor(e){this.context=e;this.babelParser=new Kn,this.treeSitterParser=new Jn(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Bn(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});import{readFileSync as wv,statSync as Tv,readdirSync as xv}from"fs";import{join as vv,extname as Cv}from"path";var Qn,Eg=h(()=>{"use strict";c();be();Qn=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=xv(e,{withFileTypes:!0});for(let n of o){let s=vv(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(Cv(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=Tv(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=wv(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 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 kv,W,Nt,be=h(()=>{"use strict";c();Tg();$g();Eg();kv=new Hn,W=new Vn(kv),Nt=new Qn});import{readFileSync as Sv,statSync as Pv,readdirSync as _v}from"fs";import{join as Rv,extname as $v}from"path";async function Dg(r,e,t){try{let o=Sv(r,"utf-8");return await W.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function Mg(r,e,t){let o=[];try{let n=_v(r,{withFileTypes:!0});for(let s of n){let i=Rv(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await Mg(i,e,t);o.push(...a)}else if(s.isFile()&&Ev.includes($v(s.name))){let a=await Dg(i,e,t);o.push(...a)}}}}catch{}return o}async function Dv(r){let e=r.symbol,t=r.path,o=r.kind;if(y(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${o??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let n=Pv(t),s;if(n.isDirectory())s=await Mg(t,e,o);else if(n.isFile())s=await Dg(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 Ev,on,Si=h(()=>{"use strict";c();fg();be();S();Ev=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];on={name:cg,displayName:pg,description:mg,parameters:ug,category:dg,execute:Dv}});var Ag,Ng,Og,Ig,jg,Lg=h(()=>{"use strict";c();Ag="coding.get_symbols",Ng="Get Symbols",Og="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Ig="coding",jg={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});import{readFileSync as Mv}from"fs";async function Av(r){let e=r.file,t=r.kind;if(y(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=Mv(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 nn,Pi=h(()=>{"use strict";c();Lg();be();S();nn={name:Ag,displayName:Ng,description:Og,parameters:jg,category:Ig,execute:Av}});var Fg,qg,Wg,Ug,Gg,Bg=h(()=>{"use strict";c();Fg="coding.get_imports",qg="Get Imports",Wg="List all import statements in a JavaScript/TypeScript file",Ug="coding",Gg={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as Nv}from"fs";async function Ov(r){let e=r.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=Nv(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 rn,_i=h(()=>{"use strict";c();Bg();be();S();rn={name:Fg,displayName:qg,description:Wg,parameters:Gg,category:Ug,execute:Ov}});var zg,Hg,Kg,Jg,Vg,Qg=h(()=>{"use strict";c();zg="coding.find_references",Hg="Find References",Kg="Find all references to a symbol across JavaScript/TypeScript files",Jg="coding",Vg={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});import{readFileSync as Iv,statSync as jv}from"fs";async function Xg(r,e,t){try{let o=Iv(r,"utf-8");return await W.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function Lv(r,e,t){let o=[];await Nt.buildIndex(r);let n=await Nt.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await Xg(s,e,t);o.push(...i)}return o}async function Fv(r){let e=r.symbol,t=r.path,o=r.includeDeclaration===!0;if(y(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${o}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let n=jv(t),s;if(n.isDirectory())s=await Lv(t,e,o);else if(n.isFile())s=await Xg(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 sn,Ri=h(()=>{"use strict";c();Qg();be();S();sn={name:zg,displayName:Hg,description:Kg,parameters:Vg,category:Jg,execute:Fv}});var Yg,Zg,eh,th,oh,nh=h(()=>{"use strict";c();Yg="coding.go_to_definition",Zg="Go To Definition",eh="Jump to the definition of a symbol at a specific location in a file",th="coding",oh={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});import{readFileSync as rh,statSync as qv}from"fs";import{dirname as Wv}from"path";async function Uv(r,e,t){try{let o=rh(r,"utf-8");return await W.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function sh(r,e){try{let t=rh(r,"utf-8");return await W.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function Gv(r,e){await Nt.buildIndex(r);let t=await Nt.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await sh(o,e);if(n)return n}return null}async function Bv(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 Uv(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await sh(e,s);if(!i){let a=n||Wv(e);qv(a).isDirectory()&&(i=await Gv(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 an,$i=h(()=>{"use strict";c();nh();be();an={name:Yg,displayName:Zg,description:eh,parameters:oh,category:th,execute:Bv}});var ih,ah,lh,ch,ph,mh=h(()=>{"use strict";c();ih="coding.multi_file_edit",ah="Multi-File Edit",lh="Edit multiple files atomically with rollback on failure",ch="coding",ph={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});import{readFileSync as zv,writeFileSync as dh,existsSync as Hv}from"fs";async function Kv(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(!Hv(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=zv(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(Jv(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)}dh(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{dh(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 Jv(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ln,Ei=h(()=>{"use strict";c();mh();ln={name:ih,displayName:ah,description:lh,parameters:ph,category:ch,execute:Kv,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var uh,fh,gh,hh,yh,bh=h(()=>{"use strict";c();uh="coding.refactor_rename",fh="Refactor Rename",gh="Rename a symbol across the entire codebase intelligently",hh="coding",yh={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});import{readFileSync as Vv,writeFileSync as Qv,readdirSync as Xv}from"fs";import{join as Yv,extname as Zv}from"path";import{parse as eC}from"@babel/parser";import*as Di from"@babel/traverse";function nC(r,e,t,o){let n=[];try{let s=Vv(r,"utf-8"),i=s.split(`
294
- `),a=eC(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),l=[];if(tC(a,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,d=p.node.loc?.start.column||0;l.push({line:m,column:d,length:e.length}),n.push({file:r,line:m,column:d,oldName:e,newName:t})}}}),!o&&l.length>0){l.sort((m,d)=>m.line!==d.line?d.line-m.line:d.column-m.column);let p=[...i];for(let m of l){let d=m.line-1;if(d>=0&&d<p.length){let g=p[d],b=g.substring(0,m.column),w=g.substring(m.column+m.length);p[d]=b+t+w}}Qv(r,p.join(`
295
- `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function wh(r,e,t,o){let n=[];try{let s=Xv(r,{withFileTypes:!0});for(let i of s){let a=Yv(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...wh(a,e,t,o));else if(i.isFile()&&oC.includes(Zv(i.name))){let l=nC(a,e,t,o);l.occurrences>0&&n.push(l)}}}}catch{}return n}async function rC(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=wh(o,e,t,n),i=s.reduce((l,p)=>l+p.occurrences,0),a=s.length;return JSON.stringify({success:!0,dryRun:n,oldName:e,newName:t,filesAffected:a,totalOccurrences:i,changes:s},null,2)}var tC,oC,cn,Mi=h(()=>{"use strict";c();bh();tC=Di.default||Di,oC=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];cn={name:uh,displayName:fh,description:gh,parameters:yh,category:hh,execute:rC,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var Th,xh,vh,Ch,kh,Sh=h(()=>{"use strict";c();Th="coding.get_outline",xh="Get File Outline",vh="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",Ch="coding",kh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as sC,statSync as iC}from"fs";async function aC(r){let e=r.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!iC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=sC(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 pn,Ai=h(()=>{"use strict";c();Sh();be();S();pn={name:Th,displayName:xh,description:vh,parameters:kh,category:Ch,execute:aC}});var Ph,_h,Rh,$h,Eh,Dh=h(()=>{"use strict";c();Ph="coding.get_diagnostics",_h="Get File Diagnostics",Rh="Gets syntax errors and warnings for a file utilizing AST parsing.",$h="coding",Eh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as lC,statSync as cC}from"fs";async function pC(r){let e=r.file;if(!e)throw new Error("file is required");try{if(!cC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=lC(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 mn,Ni=h(()=>{"use strict";c();Dh();be();mn={name:Ph,displayName:_h,description:Rh,parameters:Eh,category:$h,execute:pC}});var Mh,Ah,Nh,Oh,Ih,jh=h(()=>{"use strict";c();Mh="coding.get_exports",Ah="Get File Exports",Nh="Lists all symbols exported by a file.",Oh="coding",Ih={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as mC,statSync as dC}from"fs";async function uC(r){let e=r.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!dC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=mC(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 dn,Oi=h(()=>{"use strict";c();jh();be();S();dn={name:Mh,displayName:Ah,description:Nh,parameters:Ih,category:Oh,execute:uC}});var Lh,Fh,qh,Wh,Uh,Gh=h(()=>{"use strict";c();Lh="coding.extract_function",Fh="Extract Function",qh="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Wh="coding",Uh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});import{readFileSync as fC,statSync as gC}from"fs";async function hC(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(!gC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=fC(e,"utf-8"),l=W.getParser(e);if(!l.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await l.extractFunction({filePath:e,content:a},t,o,n,s,i);return JSON.stringify({file:e,result:p},null,2)}catch(a){throw new Error(`Failed to extract function from file "${e}": ${a.message}`)}}var un,Ii=h(()=>{"use strict";c();Gh();be();un={name:Lh,displayName:Fh,description:qh,parameters:Uh,category:Wh,execute:hC}});var Bh,zh,Hh,Kh,Jh,Vh=h(()=>{"use strict";c();Bh="coding.get_call_hierarchy",zh="Get Call Hierarchy",Hh="Shows callers and callees of a specific function or method.",Kh="coding",Jh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});import{readFileSync as yC,statSync as bC}from"fs";async function wC(r){let e=r.file,t=r.line,o=r.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");try{if(!bC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=yC(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 fn,ji=h(()=>{"use strict";c();Vh();be();fn={name:Bh,displayName:zh,description:Hh,parameters:Jh,category:Kh,execute:wC}});var Xh={};ne(Xh,{codingExtractFunctionTool:()=>un,codingFindReferencesTool:()=>sn,codingFindSymbolTool:()=>on,codingGetCallHierarchyTool:()=>fn,codingGetDiagnosticsTool:()=>mn,codingGetExportsTool:()=>dn,codingGetImportsTool:()=>rn,codingGetOutlineTool:()=>pn,codingGetSymbolsTool:()=>nn,codingGoToDefinitionTool:()=>an,codingMultiFileEditTool:()=>ln,codingRefactorRenameTool:()=>cn,codingToolsProject:()=>Qh});var Qh,Li=h(()=>{"use strict";c();Si();Pi();_i();Ri();$i();Ei();Mi();Ai();Ni();Oi();Ii();ji();Si();Pi();_i();Ri();$i();Ei();Mi();Ai();Ni();Oi();Ii();ji();Qh={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:[on,nn,rn,sn,an,pn,mn,dn,un,fn,ln,cn],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var Yh,Zh=h(()=>{"use strict";c();Yh={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});import{simpleGit as TC}from"simple-git";function G(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return TC(e)}var Pe=h(()=>{"use strict";c()});var Xn,ey=h(()=>{"use strict";c();Zh();Pe();Xn={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:Yh,execute:async r=>{let e=r.path;try{let o=await G().status(e?[e]:[]);if(o.isClean())return"Working tree clean";let n=[];return n.push(`Branch: ${o.current}`),o.tracking&&n.push(`Tracking: ${o.tracking}`),o.ahead>0&&n.push(`Ahead: ${o.ahead}`),o.behind>0&&n.push(`Behind: ${o.behind}`),n.push("---"),o.conflicted.length>0&&n.push(`Conflicted: ${o.conflicted.join(", ")}`),o.created.length>0&&n.push(`Created: ${o.created.join(", ")}`),o.deleted.length>0&&n.push(`Deleted: ${o.deleted.join(", ")}`),o.modified.length>0&&n.push(`Modified: ${o.modified.join(", ")}`),o.renamed.length>0&&n.push(`Renamed: ${o.renamed.map(s=>`${s.from} -> ${s.to}`).join(", ")}`),o.staged.length>0&&n.push(`Staged: ${o.staged.join(", ")}`),o.not_added.length>0&&n.push(`Untracked: ${o.not_added.join(", ")}`),n.join(`
296
- `)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var ty,oy=h(()=>{"use strict";c();ty={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 Yn,ny=h(()=>{"use strict";c();oy();Pe();Yn={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:ty,execute:async r=>{let e=r.path,t=r.base,o=r.head,n=r.staged,s=r.cloneDir;try{let i=G(s),a=[];if(t||o){if(!t||!o)return"Error getting git diff: both base and head are required when comparing revisions.";a.push(`${t}...${o}`)}n&&a.push("--cached"),e&&a.push("--",e);let l=await i.diff(a);return l||"No changes found."}catch(i){return`Error getting git diff: ${i instanceof Error?i.message:String(i)}`}}}});var ry,sy=h(()=>{"use strict";c();ry={type:"object",properties:{maxCount:{type:"number",description:"Maximum number of commits to return. Defaults to 10 to prevent large outputs.",default:10},path:{type:"string",description:"Optional path to get the log for specific file or directory."},cloneDir:{type:"string",description:"Optional local repository directory, typically the cloneDir returned by git.clone. When provided, this tool runs in that repository instead of the current working directory."}}}});var Zn,iy=h(()=>{"use strict";c();sy();Pe();Zn={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:ry,execute:async r=>{let e=r.maxCount||10,t=r.path,o=r.cloneDir;try{let n=G(o),s={maxCount:e};t&&(s.file=t);let i=await n.log(s);return i.all.length===0?"No commits found.":i.all.map(a=>`Commit: ${a.hash}
293
+ `,g=`${i}();`),{newFunction:d,replacementCall:g}}async getCallHierarchy(e,t,o){let n=await this.getSymbolAtPosition(e,t,o);if(!n)return null;let i=(await this.findReferences(e,n,!1)).map(a=>({file:a.file,name:a.context.trim()||"<anonymous>",line:a.line,column:a.column}));return{file:e.filePath,name:n,line:t,column:o,callers:i,callees:[]}}}});var Un,bg=h(()=>{"use strict";l();fi();pg();yg();Un=class{constructor(e){this.context=e;this.babelParser=new qn,this.treeSitterParser=new Wn(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Ln(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});import{readFileSync as cv,statSync as pv,readdirSync as mv}from"fs";import{join as dv,extname as uv}from"path";var Gn,wg=h(()=>{"use strict";l();we();Gn=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=mv(e,{withFileTypes:!0});for(let n of o){let s=dv(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(uv(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=pv(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=cv(e,"utf-8"),s=j.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 fv,j,Mt,we=h(()=>{"use strict";l();cg();bg();wg();fv=new Fn,j=new Un(fv),Mt=new Gn});import{readFileSync as gv,statSync as hv,readdirSync as yv}from"fs";import{join as bv,extname as wv}from"path";async function Tg(r,e,t){try{let o=gv(r,"utf-8");return await j.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function xg(r,e,t){let o=[];try{let n=yv(r,{withFileTypes:!0});for(let s of n){let i=bv(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await xg(i,e,t);o.push(...a)}else if(s.isFile()&&Tv.includes(wv(s.name))){let a=await Tg(i,e,t);o.push(...a)}}}}catch{}return o}async function xv(r){let e=r.symbol,t=r.path,o=r.kind;if(y(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${o??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let n=hv(t),s;if(n.isDirectory())s=await xg(t,e,o);else if(n.isFile())s=await Tg(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 Tv,Yo,bi=h(()=>{"use strict";l();ng();we();S();Tv=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Yo={name:Yf,displayName:Zf,description:eg,parameters:og,category:tg,execute:xv}});var vg,Cg,kg,Sg,Pg,_g=h(()=>{"use strict";l();vg="coding.get_symbols",Cg="Get Symbols",kg="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Sg="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"]}});import{readFileSync as vv}from"fs";async function Cv(r){let e=r.file,t=r.kind;if(y(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=vv(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 Zo,wi=h(()=>{"use strict";l();_g();we();S();Zo={name:vg,displayName:Cg,description:kg,parameters:Pg,category:Sg,execute:Cv}});var Rg,$g,Eg,Dg,Mg,Ag=h(()=>{"use strict";l();Rg="coding.get_imports",$g="Get Imports",Eg="List all import statements in a JavaScript/TypeScript file",Dg="coding",Mg={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as kv}from"fs";async function Sv(r){let e=r.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=kv(e,"utf-8"),n=await j.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 en,Ti=h(()=>{"use strict";l();Ag();we();S();en={name:Rg,displayName:$g,description:Eg,parameters:Mg,category:Dg,execute:Sv}});var Ng,Og,Ig,Lg,jg,Fg=h(()=>{"use strict";l();Ng="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"]}});import{readFileSync as Pv,statSync as _v}from"fs";async function qg(r,e,t){try{let o=Pv(r,"utf-8");return await j.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function Rv(r,e,t){let o=[];await Mt.buildIndex(r);let n=await Mt.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await qg(s,e,t);o.push(...i)}return o}async function $v(r){let e=r.symbol,t=r.path,o=r.includeDeclaration===!0;if(y(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${o}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let n=_v(t),s;if(n.isDirectory())s=await Rv(t,e,o);else if(n.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 tn,xi=h(()=>{"use strict";l();Fg();we();S();tn={name:Ng,displayName:Og,description:Ig,parameters:jg,category:Lg,execute:$v}});var Wg,Ug,Gg,Bg,zg,Hg=h(()=>{"use strict";l();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"]}});import{readFileSync as Kg,statSync as Ev}from"fs";import{dirname as Dv}from"path";async function Mv(r,e,t){try{let o=Kg(r,"utf-8");return await j.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function Jg(r,e){try{let t=Kg(r,"utf-8");return await j.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function Av(r,e){await Mt.buildIndex(r);let t=await Mt.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await Jg(o,e);if(n)return n}return null}async function Nv(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 Mv(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=n||Dv(e);Ev(a).isDirectory()&&(i=await Av(a,s))}return JSON.stringify(i?{found:!0,symbol:s,definition:i}:{found:!1,symbol:s,message:`Definition not found for symbol "${s}"`},null,2)}var on,vi=h(()=>{"use strict";l();Hg();we();on={name:Wg,displayName:Ug,description:Gg,parameters:zg,category:Bg,execute:Nv}});var Vg,Qg,Xg,Yg,Zg,eh=h(()=>{"use strict";l();Vg="coding.multi_file_edit",Qg="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"]}});import{readFileSync as Ov,writeFileSync as th,existsSync as Iv}from"fs";async function Lv(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(!Iv(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=Ov(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(jv(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)}th(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{th(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 jv(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var nn,Ci=h(()=>{"use strict";l();eh();nn={name:Vg,displayName:Qg,description:Xg,parameters:Zg,category:Yg,execute:Lv,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var oh,nh,rh,sh,ih,ah=h(()=>{"use strict";l();oh="coding.refactor_rename",nh="Refactor Rename",rh="Rename a symbol across the entire codebase intelligently",sh="coding",ih={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});import{readFileSync as Fv,writeFileSync as qv,readdirSync as Wv}from"fs";import{join as Uv,extname as Gv}from"path";import{parse as Bv}from"@babel/parser";import*as ki from"@babel/traverse";function Kv(r,e,t,o){let n=[];try{let s=Fv(r,"utf-8"),i=s.split(`
294
+ `),a=Bv(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(zv(a,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,d=p.node.loc?.start.column||0;c.push({line:m,column:d,length:e.length}),n.push({file:r,line:m,column:d,oldName:e,newName:t})}}}),!o&&c.length>0){c.sort((m,d)=>m.line!==d.line?d.line-m.line:d.column-m.column);let p=[...i];for(let m of c){let d=m.line-1;if(d>=0&&d<p.length){let g=p[d],w=g.substring(0,m.column),b=g.substring(m.column+m.length);p[d]=w+t+b}}qv(r,p.join(`
295
+ `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function lh(r,e,t,o){let n=[];try{let s=Wv(r,{withFileTypes:!0});for(let i of s){let a=Uv(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...lh(a,e,t,o));else if(i.isFile()&&Hv.includes(Gv(i.name))){let c=Kv(a,e,t,o);c.occurrences>0&&n.push(c)}}}}catch{}return n}async function Jv(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=lh(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 zv,Hv,rn,Si=h(()=>{"use strict";l();ah();zv=ki.default||ki,Hv=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];rn={name:oh,displayName:nh,description:rh,parameters:ih,category:sh,execute:Jv,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=h(()=>{"use strict";l();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"]}});import{readFileSync as Vv,statSync as Qv}from"fs";async function Xv(r){let e=r.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!Qv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Vv(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 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 sn,Pi=h(()=>{"use strict";l();fh();we();S();sn={name:ch,displayName:ph,description:mh,parameters:uh,category:dh,execute:Xv}});var gh,hh,yh,bh,wh,Th=h(()=>{"use strict";l();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"]}});import{readFileSync as Yv,statSync as Zv}from"fs";async function eC(r){let e=r.file;if(!e)throw new Error("file is required");try{if(!Zv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Yv(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 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 an,_i=h(()=>{"use strict";l();Th();we();an={name:gh,displayName:hh,description:yh,parameters:wh,category:bh,execute:eC}});var xh,vh,Ch,kh,Sh,Ph=h(()=>{"use strict";l();xh="coding.get_exports",vh="Get File Exports",Ch="Lists all symbols exported by a file.",kh="coding",Sh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as tC,statSync as oC}from"fs";async function nC(r){let e=r.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!oC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=tC(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 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 ln,Ri=h(()=>{"use strict";l();Ph();we();S();ln={name:xh,displayName:vh,description:Ch,parameters:Sh,category:kh,execute:nC}});var _h,Rh,$h,Eh,Dh,Mh=h(()=>{"use strict";l();_h="coding.extract_function",Rh="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"]}});import{readFileSync as rC,statSync as sC}from"fs";async function iC(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(!sC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=rC(e,"utf-8"),c=j.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 cn,$i=h(()=>{"use strict";l();Mh();we();cn={name:_h,displayName:Rh,description:$h,parameters:Dh,category:Eh,execute:iC}});var Ah,Nh,Oh,Ih,Lh,jh=h(()=>{"use strict";l();Ah="coding.get_call_hierarchy",Nh="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"]}});import{readFileSync as aC,statSync as lC}from"fs";async function cC(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(!lC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=aC(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: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 pn,Ei=h(()=>{"use strict";l();jh();we();pn={name:Ah,displayName:Nh,description:Oh,parameters:Lh,category:Ih,execute:cC}});var qh={};oe(qh,{codingExtractFunctionTool:()=>cn,codingFindReferencesTool:()=>tn,codingFindSymbolTool:()=>Yo,codingGetCallHierarchyTool:()=>pn,codingGetDiagnosticsTool:()=>an,codingGetExportsTool:()=>ln,codingGetImportsTool:()=>en,codingGetOutlineTool:()=>sn,codingGetSymbolsTool:()=>Zo,codingGoToDefinitionTool:()=>on,codingMultiFileEditTool:()=>nn,codingRefactorRenameTool:()=>rn,codingToolsProject:()=>Fh});var Fh,Di=h(()=>{"use strict";l();bi();wi();Ti();xi();vi();Ci();Si();Pi();_i();Ri();$i();Ei();bi();wi();Ti();xi();vi();Ci();Si();Pi();_i();Ri();$i();Ei();Fh={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:[Yo,Zo,en,tn,on,sn,an,ln,cn,pn,nn,rn],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var Wh,Uh=h(()=>{"use strict";l();Wh={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});import{simpleGit as pC}from"simple-git";function U(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return pC(e)}var Se=h(()=>{"use strict";l()});var Bn,Gh=h(()=>{"use strict";l();Uh();Se();Bn={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:Wh,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(`
296
+ `)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var Bh,zh=h(()=>{"use strict";l();Bh={type:"object",properties:{path:{type:"string",description:"Optional path to get the diff for. If omitted, gets the diff for the entire repository."},base:{type:"string",description:"Optional base commit/ref for comparing two revisions. When used with head, runs git diff base...head."},head:{type:"string",description:"Optional head commit/ref for comparing two revisions. When used with base, runs git diff base...head."},staged:{type:"boolean",description:"If true, gets the diff of staged changes instead of unstaged changes.",default:!1},cloneDir:{type:"string",description:"Optional local repository directory, typically the cloneDir returned by git.clone. When provided, this tool runs in that repository instead of the current working directory."}}}});var zn,Hh=h(()=>{"use strict";l();zh();Se();zn={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:Bh,execute:async r=>{let e=r.path,t=r.base,o=r.head,n=r.staged,s=r.cloneDir;try{let i=U(s),a=[];if(t||o){if(!t||!o)return"Error getting git diff: both base and head are required when comparing revisions.";a.push(`${t}...${o}`)}n&&a.push("--cached"),e&&a.push("--",e);let c=await i.diff(a);return c||"No changes found."}catch(i){return`Error getting git diff: ${i instanceof Error?i.message:String(i)}`}}}});var Kh,Jh=h(()=>{"use strict";l();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."},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 Hn,Vh=h(()=>{"use strict";l();Jh();Se();Hn={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:Kh,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}
297
297
  Author: ${a.author_name} <${a.author_email}>
298
298
  Date: ${a.date}
299
299
  Message: ${a.message}
300
300
  `).join(`---
301
- `)}catch(n){return`Error getting git log: ${n instanceof Error?n.message:String(n)}`}}}});var ay,ly=h(()=>{"use strict";c();ay={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var er,cy=h(()=>{"use strict";c();ly();Pe();er={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:ay,execute:async r=>{let e=r.path;try{return await G().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var py,my=h(()=>{"use strict";c();py={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var tr,dy=h(()=>{"use strict";c();my();Pe();tr={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:py,execute:async r=>{let e=r.message;try{let o=await G().commit(e);return o.commit?`Successfully committed changes.
301
+ `)}catch(n){return`Error getting git log: ${n instanceof Error?n.message:String(n)}`}}}});var Qh,Xh=h(()=>{"use strict";l();Qh={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Kn,Yh=h(()=>{"use strict";l();Xh();Se();Kn={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:Qh,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 Zh,ey=h(()=>{"use strict";l();Zh={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Jn,ty=h(()=>{"use strict";l();ey();Se();Jn={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Zh,execute:async r=>{let e=r.message;try{let o=await U().commit(e);return o.commit?`Successfully committed changes.
302
302
  Commit: ${o.commit}
303
303
  Branch: ${o.branch}
304
- Summary: ${o.summary.changes} changes, ${o.summary.insertions} insertions, ${o.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will create a permanent commit in the repository history.",showArgs:["message"]}}});var uy,fy=h(()=>{"use strict";c();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 or,gy=h(()=>{"use strict";c();fy();Pe();or={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=G(o),s=["blame"];return t&&s.push(t),s.push("--",e),await n.raw(s)}catch(n){return`Error running git blame: ${n instanceof Error?n.message:String(n)}`}}}});var hy,yy=h(()=>{"use strict";c();hy={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var nr,by=h(()=>{"use strict";c();yy();Pe();nr={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:hy,execute:async r=>{let e=r.remote;try{let t=G(),o=e?["-a"]:[],n=await t.branch(o);return`Current Branch: ${n.current}
304
+ Summary: ${o.summary.changes} changes, ${o.summary.insertions} insertions, ${o.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will create a permanent commit in the repository history.",showArgs:["message"]}}});var oy,ny=h(()=>{"use strict";l();oy={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 Vn,ry=h(()=>{"use strict";l();ny();Se();Vn={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 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 sy,iy=h(()=>{"use strict";l();sy={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Qn,ay=h(()=>{"use strict";l();iy();Se();Qn={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:sy,execute:async r=>{let e=r.remote;try{let t=U(),o=e?["-a"]:[],n=await t.branch(o);return`Current Branch: ${n.current}
305
305
 
306
306
  Branches:
307
307
  ${n.all.join(`
308
- `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var wy,Ty=h(()=>{"use strict";c();wy={type:"object",properties:{name:{type:"string",description:"Name of the new branch."},checkout:{type:"boolean",description:"Whether to checkout the new branch after creating it.",default:!1},startPoint:{type:"string",description:"Optional start point (commit hash or branch name) for the new branch."}},required:["name"]}});var rr,xy=h(()=>{"use strict";c();Ty();Pe();rr={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:wy,execute:async r=>{let e=r.name,t=r.checkout,o=r.startPoint;try{let n=G();return t?(o?await n.checkoutBranch(e,o):await n.checkoutLocalBranch(e),`Successfully created and switched to branch: ${e}`):(o?await n.branch([e,o]):await n.branch([e]),`Successfully created branch: ${e}`)}catch(n){return`Error creating branch: ${n instanceof Error?n.message:String(n)}`}}}});var vy,Cy=h(()=>{"use strict";c();vy={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var sr,ky=h(()=>{"use strict";c();Cy();Pe();sr={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:vy,execute:async r=>{let e=r.branch;try{return await G().checkout(e),`Successfully checked out: ${e}`}catch(t){return`Error checking out branch: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will switch branches, potentially losing uncommitted changes.",showArgs:["branch"]}}});var Sy,Py=h(()=>{"use strict";c();Sy={type:"object",properties:{repo:{type:"string",description:'The repository to clone in "owner/repo" format (e.g., "microsoft/typescript").'},sha:{type:"string",description:"The commit SHA to checkout (always use SHAs, never branch names \u2014 handles force-pushes correctly)."},filter:{type:"string",description:'Git partial clone filter. "blob:none" (default) skips file blobs for a fast clone \u2014 blobs are fetched on demand when you read files or run git blame. Use "none" when you need immediate access to all file contents without extra fetches (e.g. heavy blame across many files).',default:"blob:none"},depth:{type:"number",description:"Commit history depth. Default 50 is enough for most PR reviews. Use 0 for full history when you need complete git log or blame across a long-lived file.",default:50},cloneRoot:{type:"string",description:"Override the local directory where clones are stored. Leave unset in almost all cases \u2014 the default is managed automatically."}},required:["repo","sha"]}});import*as de from"fs/promises";import*as ar from"path";async function CC(r){for(;ir.has(r);)await ir.get(r);let e,t=new Promise(o=>{e=o});return ir.set(r,t),()=>{ir.delete(r),e()}}async function _y(r){let e=0,t=await de.readdir(r,{withFileTypes:!0});for(let o of t){let n=ar.join(r,o.name);if(o.isDirectory())e+=await _y(n);else if(o.isFile()){let s=await de.stat(n);e+=s.size}}return e}async function kC(r,e){let t=e-r;for(;Be>t&&ze.size>0;){let o=null,n=null;for(let[s,i]of ze)(!o||i.lastAccessedAt<o.lastAccessedAt)&&(o=i,n=s);if(!n||!o)break;try{await de.rm(o.cloneDir,{recursive:!0,force:!0}),Be=Math.max(0,Be-o.sizeBytes),ze.delete(n)}catch{break}}}async function SC(r,e,t,o,n){let i=`https://x-access-token:${await B(r)}@github.com/${r}.git`,a=r.replace("/","_"),l=ar.resolve(n,a),p=G(n),m=ze.get(r);if(m)try{if(await de.access(l),m.sha===e)return m.lastAccessedAt=Date.now(),l;await de.rm(l,{recursive:!0,force:!0}),Be=Math.max(0,Be-m.sizeBytes),ze.delete(r)}catch{Be=Math.max(0,Be-m.sizeBytes),ze.delete(r)}else try{await de.access(l),await de.rm(l,{recursive:!0,force:!0})}catch{}let d=["--no-checkout"];o>0&&d.push("--depth",o.toString()),t&&t!=="none"&&d.push("--filter",t);try{await p.clone(i,a,d);let g=G(l);try{let w=["origin",e];o>0&&w.push("--depth",o.toString()),await g.fetch(w)}catch{}await g.checkout(["--force",e]);let b=await _y(l);return Be+=b,ze.set(r,{cloneDir:l,repo:r,sha:e,sizeBytes:b,lastAccessedAt:Date.now()}),l}catch(g){try{await de.rm(l,{recursive:!0,force:!0})}catch{}throw g}}function PC(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}var xC,vC,ze,ir,Be,lr,Ry=h(()=>{"use strict";c();Py();Pe();ke();xC=".toolpack/clones",vC=5e9,ze=new Map,ir=new Map,Be=0;lr={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:Sy,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??xC,i=parseInt(process.env.SENTINEL_CLONE_MAX_BYTES??"0",10)||vC;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 de.mkdir(s,{recursive:!0});let l=await CC(e);try{let p=ze.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 kC(1e8,i);let m=await SC(e,t,o,n,s);return JSON.stringify({cloneDir:m,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."})}catch(p){return`Error cloning repository: ${PC(p)}`}finally{l()}}}});var Ey={};ne(Ey,{gitAddTool:()=>er,gitBlameTool:()=>or,gitBranchCreateTool:()=>rr,gitBranchListTool:()=>nr,gitCheckoutTool:()=>sr,gitCloneTool:()=>lr,gitCommitTool:()=>tr,gitDiffTool:()=>Yn,gitLogTool:()=>Zn,gitStatusTool:()=>Xn,gitToolsProject:()=>$y});var $y,Fi=h(()=>{"use strict";c();ey();ny();iy();cy();dy();gy();by();xy();ky();Ry();$y={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:[Xn,Yn,Zn,er,tr,or,nr,rr,sr,lr],dependencies:{"simple-git":"^3.27.0"}}});var Dy,My=h(()=>{"use strict";c();Dy={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});import*as Ay from"diff";var cr,Ny=h(()=>{"use strict";c();My();S();cr={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:Dy,execute:async r=>{let e=r.oldContent,t=r.newContent,o=r.fileName||"file",n=r.contextLines??4;y(`[diff.create] execute fileName="${o}" contextLines=${n}`);try{return Ay.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var Oy,Iy=h(()=>{"use strict";c();Oy={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});import*as Ly from"diff";import{promises as jy}from"fs";var pr,Fy=h(()=>{"use strict";c();Iy();S();pr={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Oy,execute:async r=>{let e=r.path,t=r.patch;y(`[diff.apply] execute path="${e}"`);try{let o=await jy.readFile(e,"utf8"),n=Ly.applyPatch(o,t);return n===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await jy.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 qy,Wy=h(()=>{"use strict";c();qy={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});import*as Uy from"diff";import{promises as _C}from"fs";var mr,Gy=h(()=>{"use strict";c();Wy();mr={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:qy,execute:async r=>{let e=r.path,t=r.patch;try{let o=await _C.readFile(e,"utf8"),n=Uy.applyPatch(o,t);return n===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
308
+ `)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var ly,cy=h(()=>{"use strict";l();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 Xn,py=h(()=>{"use strict";l();cy();Se();Xn={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:ly,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 my,dy=h(()=>{"use strict";l();my={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Yn,uy=h(()=>{"use strict";l();dy();Se();Yn={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:my,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 fy,gy=h(()=>{"use strict";l();fy={type:"object",properties:{repo:{type:"string",description:'The repository to clone in "owner/repo" format (e.g., "microsoft/typescript").'},sha:{type:"string",description:"The commit SHA to checkout (always use SHAs, never branch names \u2014 handles force-pushes correctly)."},filter:{type:"string",description:'Git partial clone filter. "blob:none" (default) skips file blobs for a fast clone \u2014 blobs are fetched on demand when you read files or run git blame. Use "none" when you need immediate access to all file contents without extra fetches (e.g. heavy blame across many files).',default:"blob:none"},depth:{type:"number",description:"Commit history depth. Default 50 is enough for most PR reviews. Use 0 for full history when you need complete git log or blame across a long-lived file.",default:50},cloneRoot:{type:"string",description:"Override the local directory where clones are stored. Leave unset in almost all cases \u2014 the default is managed automatically."}},required:["repo","sha"]}});import*as he from"fs/promises";import*as Zn from"path";async function hy(r){let e=0,t=await he.readdir(r,{withFileTypes:!0});for(let o of t){let n=Zn.join(r,o.name);if(o.isDirectory())e+=await hy(n);else if(o.isFile()){let s=await he.stat(n);e+=s.size}}return e}async function uC(r,e,t,o,n,s,i,a){let p=`https://x-access-token:${await B(e,void 0,i,a)}@github.com/${e}.git`,m=e.replace("/","_"),d=Zn.resolve(s,m),g=U(s),w=r.registry.get(e);if(w)try{if(await he.access(d),w.sha===t)return w.lastAccessedAt=Date.now(),d;await he.rm(d,{recursive:!0,force:!0}),r.totalBytes=Math.max(0,r.totalBytes-w.sizeBytes),r.registry.delete(e)}catch{r.totalBytes=Math.max(0,r.totalBytes-w.sizeBytes),r.registry.delete(e)}else try{await he.access(d),await he.rm(d,{recursive:!0,force:!0})}catch{}let b=["--no-checkout"];n>0&&b.push("--depth",n.toString()),o&&o!=="none"&&b.push("--filter",o);try{await g.clone(p,m,b);let T=U(d);try{let v=["origin",t];n>0&&v.push("--depth",n.toString()),await T.fetch(v)}catch{}await T.checkout(["--force",t]);let k=await hy(d);return r.totalBytes+=k,r.registry.set(e,{cloneDir:d,repo:e,sha:t,sizeBytes:k,lastAccessedAt:Date.now()}),d}catch(T){try{await he.rm(d,{recursive:!0,force:!0})}catch{}throw T}}function fC(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}function Mi(r){return{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:fy,execute:async(e,t)=>{let o=e.repo,n=e.sha,s=e.filter??"blob:none",i=e.depth??50,a=t?.config?.gitClone,c=e.cloneRoot??a?.cloneRoot??process.env.TOOLPACK_GIT_CLONE_ROOT??mC,p=parseInt(process.env.TOOLPACK_GIT_CLONE_MAX_BYTES??"0",10)||dC,m=a?.maxBytes??p;if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(o))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(n))return"Error: sha must be a valid commit SHA (7-40 hex characters)";await he.mkdir(c,{recursive:!0});let d=await r.acquireMutex(o);try{let g=r.registry.get(o);if(g&&g.sha===n)return g.lastAccessedAt=Date.now(),JSON.stringify({cloneDir:g.cloneDir,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."});await r.evictIfNeeded(1e8,m);let w=await uC(r,o,n,s,i,c,t?.githubTokenStore,t?.config?.credentials);return JSON.stringify({cloneDir:w,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."})}catch(g){return`Error cloning repository: ${fC(g)}`}finally{d()}}}}var mC,dC,er,yy=h(()=>{"use strict";l();gy();Se();be();os();mC=".toolpack/clones",dC=5e9;er=Mi(Qa)});var wy={};oe(wy,{createGitCloneTool:()=>Mi,gitAddTool:()=>Kn,gitBlameTool:()=>Vn,gitBranchCreateTool:()=>Xn,gitBranchListTool:()=>Qn,gitCheckoutTool:()=>Yn,gitCloneTool:()=>er,gitCommitTool:()=>Jn,gitDiffTool:()=>zn,gitLogTool:()=>Hn,gitStatusTool:()=>Bn,gitToolsProject:()=>by});var by,Ai=h(()=>{"use strict";l();Gh();Hh();Vh();Yh();ty();ry();ay();py();uy();yy();by={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:[Bn,zn,Hn,Kn,Jn,Vn,Qn,Xn,Yn,er],dependencies:{"simple-git":"^3.27.0"}}});var Ty,xy=h(()=>{"use strict";l();Ty={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});import*as vy from"diff";var tr,Cy=h(()=>{"use strict";l();xy();S();tr={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:Ty,execute:async r=>{let e=r.oldContent,t=r.newContent,o=r.fileName||"file",n=r.contextLines??4;y(`[diff.create] execute fileName="${o}" contextLines=${n}`);try{return vy.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var ky,Sy=h(()=>{"use strict";l();ky={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});import*as _y from"diff";import{promises as Py}from"fs";var or,Ry=h(()=>{"use strict";l();Sy();S();or={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:ky,execute:async r=>{let e=r.path,t=r.patch;y(`[diff.apply] execute path="${e}"`);try{let o=await Py.readFile(e,"utf8"),n=_y.applyPatch(o,t);return n===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await Py.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 $y,Ey=h(()=>{"use strict";l();$y={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});import*as Dy from"diff";import{promises as gC}from"fs";var nr,My=h(()=>{"use strict";l();Ey();nr={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:$y,execute:async r=>{let e=r.path,t=r.patch;try{let o=await gC.readFile(e,"utf8"),n=Dy.applyPatch(o,t);return n===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
309
309
 
310
- ${n}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var zy={};ne(zy,{diffApplyTool:()=>pr,diffCreateTool:()=>cr,diffPreviewTool:()=>mr,diffToolsProject:()=>By});var By,qi=h(()=>{"use strict";c();Ny();Fy();Gy();By={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:[cr,pr,mr],dependencies:{diff:"^7.0.0"}}});var Hy,Ky=h(()=>{"use strict";c();Hy={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 He,dr=h(()=>{"use strict";c();He=class{connectionString;constructor(e){this.connectionString=e}}});import Jy from"better-sqlite3";import*as Wi from"fs";var gn,Vy=h(()=>{"use strict";c();dr();gn=class extends He{getDb(){if(!Wi.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Jy(this.connectionString,{readonly:!1})}async query(e,t=[]){let o=this.getDb();try{let n=o.prepare(e);return n.reader?n.all(t):(n.run(t),[])}finally{o.close()}}async execute(e,t=[]){let o=this.getDb();try{let s=o.prepare(e).run(t);return{changes:s.changes,lastInsertRowid:s.lastInsertRowid,raw:s}}finally{o.close()}}async getTables(){return(await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`PRAGMA table_info("${e}")`):await this.query("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")}static executeSession(e,t,o=[]){if(!Wi.existsSync(e))throw new Error(`Database file not found: ${e}`);let n=new Jy(e,{readonly:!1});try{let s=n.prepare(t);return s.reader?s.all(o):s.run(o)}finally{n.close()}}}});import RC from"pg";var ur,Qy=h(()=>{"use strict";c();dr();ur=class extends He{async getClient(){let e=new RC.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let o=await this.getClient();try{let n=this.convertSql(e);return(await o.query(n,t)).rows}finally{await o.end()}}async execute(e,t=[]){let o=await this.getClient();try{let n=this.convertSql(e),s=await o.query(n,t);return{changes:s.rowCount??0,raw:s}}finally{await o.end()}}async getTables(){return(await this.query("SELECT tablename as name FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`
310
+ ${n}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var Ny={};oe(Ny,{diffApplyTool:()=>or,diffCreateTool:()=>tr,diffPreviewTool:()=>nr,diffToolsProject:()=>Ay});var Ay,Ni=h(()=>{"use strict";l();Cy();Ry();My();Ay={manifest:{key:"diff",name:"diff-tools",displayName:"Diff and Patch",version:"1.0.0",description:"Tools to create and apply unified diff changes to files safely.",author:"Sajeer",tools:["diff.create","diff.apply","diff.preview"],category:"diff"},tools:[tr,or,nr],dependencies:{diff:"^7.0.0"}}});var Oy,Iy=h(()=>{"use strict";l();Oy={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 Be,rr=h(()=>{"use strict";l();Be=class{connectionString;constructor(e){this.connectionString=e}}});import Ly from"better-sqlite3";import*as Oi from"fs";var mn,jy=h(()=>{"use strict";l();rr();mn=class extends Be{getDb(){if(!Oi.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Ly(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(!Oi.existsSync(e))throw new Error(`Database file not found: ${e}`);let n=new Ly(e,{readonly:!1});try{let s=n.prepare(t);return s.reader?s.all(o):s.run(o)}finally{n.close()}}}});import hC from"pg";var sr,Fy=h(()=>{"use strict";l();rr();sr=class extends Be{async getClient(){let e=new hC.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(`
311
311
  SELECT column_name, data_type, is_nullable, column_default
312
312
  FROM information_schema.columns
313
313
  WHERE table_name = $1
@@ -315,14 +315,14 @@ ${n}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:Str
315
315
  SELECT table_name as name, table_type
316
316
  FROM information_schema.tables
317
317
  WHERE table_schema = 'public'
318
- `)}}});import $C from"mysql2/promise";var fr,Xy=h(()=>{"use strict";c();dr();fr=class extends He{async getConnection(){return await $C.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 te,Ke=h(()=>{"use strict";c();Vy();Qy();Xy();te=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new ur(e):e.startsWith("mysql://")?new fr(e):e.startsWith("sqlite://")?new gn(e.replace("sqlite://","")):new gn(e)}}});var gr,Yy=h(()=>{"use strict";c();Ky();Ke();S();gr={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Hy,execute:async r=>{let e=r.db,t=r.sql,o=r.params||[];y(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let s=await te.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 Zy,eb=h(()=>{"use strict";c();Zy={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 hr,tb=h(()=>{"use strict";c();eb();Ke();hr={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Zy,execute:async r=>{let e=r.db,t=r.table;try{let n=await te.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var ob,nb=h(()=>{"use strict";c();ob={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var yr,rb=h(()=>{"use strict";c();nb();Ke();yr={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:ob,execute:async r=>{let e=r.db;try{let o=await te.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var sb,ib=h(()=>{"use strict";c();sb={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 br,ab=h(()=>{"use strict";c();ib();Ke();br={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:sb,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 te.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 lb,cb=h(()=>{"use strict";c();lb={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 wr,pb=h(()=>{"use strict";c();cb();Ke();wr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:lb,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 te.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 mb,db=h(()=>{"use strict";c();mb={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 Tr,ub=h(()=>{"use strict";c();db();Ke();Tr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:mb,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await te.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 fb,gb=h(()=>{"use strict";c();fb={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 xr,hb=h(()=>{"use strict";c();gb();Ke();xr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:fb,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 te.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 bb={};ne(bb,{dbCountTool:()=>xr,dbDeleteTool:()=>Tr,dbInsertTool:()=>br,dbQueryTool:()=>gr,dbSchemaTool:()=>hr,dbTablesTool:()=>yr,dbToolsProject:()=>yb,dbUpdateTool:()=>wr});var yb,Ui=h(()=>{"use strict";c();Yy();tb();rb();ab();pb();ub();hb();yb={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:[gr,hr,yr,br,wr,Tr,xr],dependencies:{"better-sqlite3":"^11.3.0"}}});var wb,Tb=h(()=>{"use strict";c();wb={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});import{NetlifyAPI as EC}from"netlify";var Je,vr=h(()=>{"use strict";c();Je=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 EC(e)}}});var Cr,xb=h(()=>{"use strict";c();Tb();vr();S();Cr={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:wb,execute:async r=>{let e=r.siteId,t=r.dir,o=r.message;y(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let s=await Je.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 vb,Cb=h(()=>{"use strict";c();vb={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 kr,kb=h(()=>{"use strict";c();Cb();vr();kr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:vb,execute:async r=>{let e=r.siteId,t=r.deployId;try{let n=await Je.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 Sb,Pb=h(()=>{"use strict";c();Sb={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 Sr,_b=h(()=>{"use strict";c();Pb();vr();S();Sr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Sb,execute:async r=>{let e=r.siteId,t=r.limit||5;y(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let n=await Je.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 $b={};ne($b,{cloudDeployTool:()=>Cr,cloudListTool:()=>Sr,cloudStatusTool:()=>kr,cloudToolsProject:()=>Rb});var Rb,Gi=h(()=>{"use strict";c();xb();kb();_b();Rb={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:[Cr,kr,Sr],dependencies:{netlify:"^13.1.20"}}});var Eb,Db,Mb,Ab,Nb,Ob=h(()=>{"use strict";c();Eb="slack.chat.postMessage",Db="Post Slack Message",Mb="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.",Ab="slack",Nb={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 we(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 lt=h(()=>{"use strict";c()});function DC(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}}async function Te(r,e,t){let o=await fetch(`https://slack.com/api/${r}`,{method:"POST",headers:DC(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 ct=h(()=>{"use strict";c()});async function MC(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=we(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 Te("chat.postMessage",s,i),l=a.ts??"";return`Message posted. channel=${a.channel??e} ts=${l}`}var hn,Bi=h(()=>{"use strict";c();Ob();lt();ct();hn={name:Eb,displayName:Db,description:Mb,parameters:Nb,category:Ab,execute:MC}});var Ib,jb,Lb,Fb,qb,Wb=h(()=>{"use strict";c();Ib="slack.chat.postEphemeral",jb="Post Ephemeral Slack Message",Lb="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.",Fb="slack",qb={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 AC(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=we(r.token),i={channel:e,user:t,text:o};return n&&(i.thread_ts=n),await Te("chat.postEphemeral",s,i),`Ephemeral message sent to user=${t} in channel=${e}.`}var yn,zi=h(()=>{"use strict";c();Wb();lt();ct();yn={name:Ib,displayName:jb,description:Lb,parameters:qb,category:Fb,execute:AC}});var Ub,Gb,Bb,zb,Hb,Kb=h(()=>{"use strict";c();Ub="slack.reactions.add",Gb="Add Slack Reaction",Bb="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.",zb="slack",Hb={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 NC(r){let e=String(r.channel),t=String(r.timestamp),o=String(r.name),n=we(r.token);try{await Te("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 bn,Hi=h(()=>{"use strict";c();Kb();lt();ct();bn={name:Ub,displayName:Gb,description:Bb,parameters:Hb,category:zb,execute:NC}});var Jb,Vb,Qb,Xb,Yb,Zb=h(()=>{"use strict";c();Jb="slack.conversations.history",Vb="Get Slack Channel History",Qb="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.",Xb="slack",Yb={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 OC(r){let e=String(r.channel),t=typeof r.limit=="number"?Math.min(r.limit,100):10,o=we(r.token),n={channel:e,limit:t};r.oldest&&(n.oldest=String(r.oldest)),r.latest&&(n.latest=String(r.latest));let i=(await Te("conversations.history",o,n)).messages??[];return i.length===0?"No messages found.":[...i].reverse().map(l=>{let p=l.user?`user:${l.user}`:l.bot_id?`bot:${l.bot_id}`:"unknown",m=l.reply_count?` [thread: ${l.reply_count} replies]`:"",d=(l.text??"").replace(/\n/g," ").slice(0,200);return`[${l.ts}] ${p}${m}: ${d}`}).join(`
319
- `)}var wn,Ki=h(()=>{"use strict";c();Zb();lt();ct();wn={name:Jb,displayName:Vb,description:Qb,parameters:Yb,category:Xb,execute:OC}});var ew,tw,ow,nw,rw,sw=h(()=>{"use strict";c();ew="slack.conversations.replies",tw="Get Slack Thread Replies",ow="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.",nw="slack",rw={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 IC(r){let e=String(r.channel),t=String(r.ts),o=typeof r.limit=="number"?Math.min(r.limit,100):20,n=we(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 Te("conversations.replies",n,s)).messages??[];return a.length===0?"No replies found.":a.map((p,m)=>{let d=p.user?`user:${p.user}`:p.bot_id?`bot:${p.bot_id}`:"unknown",g=m===0?" [parent]":"",b=(p.text??"").replace(/\n/g," ").slice(0,200);return`[${p.ts}] ${d}${g}: ${b}`}).join(`
320
- `)}var Tn,Ji=h(()=>{"use strict";c();sw();lt();ct();Tn={name:ew,displayName:tw,description:ow,parameters:rw,category:nw,execute:IC}});var iw,aw,lw,cw,pw,mw=h(()=>{"use strict";c();iw="slack.auth.test",aw="Slack Auth Test",lw="Verify the bot token and retrieve the identity of the calling app. Returns the bot_id, user_id, team, and workspace URL. Use this when the bot_id is not configured and is needed for self-suppression or other identity checks.",cw="slack",pw={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function jC(r){let e=we(r.token),t=await Te("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 xn,Vi=h(()=>{"use strict";c();mw();lt();ct();xn={name:iw,displayName:aw,description:lw,parameters:pw,category:cw,execute:jC}});var uw={};ne(uw,{slackAuthTestTool:()=>xn,slackChatPostEphemeralTool:()=>yn,slackChatPostMessageTool:()=>hn,slackConversationsHistoryTool:()=>wn,slackConversationsRepliesTool:()=>Tn,slackReactionsAddTool:()=>bn,slackToolsProject:()=>dw});var dw,Qi=h(()=>{"use strict";c();Bi();zi();Hi();Ki();Ji();Vi();Bi();zi();Hi();Ki();Ji();Vi();dw={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:[hn,yn,bn,wn,Tn,xn]}});import{execFileSync as LC}from"child_process";function I(r,e){if(r.includes("\0")||r.includes(`
321
- `)||r.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return r}function FC(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()}`:""}
318
+ `)}}});import yC from"mysql2/promise";var ir,qy=h(()=>{"use strict";l();rr();ir=class extends Be{async getConnection(){return await yC.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 re,ze=h(()=>{"use strict";l();jy();Fy();qy();re=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new sr(e):e.startsWith("mysql://")?new ir(e):e.startsWith("sqlite://")?new mn(e.replace("sqlite://","")):new mn(e)}}});var ar,Wy=h(()=>{"use strict";l();Iy();ze();S();ar={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Oy,execute:async r=>{let e=r.db,t=r.sql,o=r.params||[];y(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let s=await re.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 Uy,Gy=h(()=>{"use strict";l();Uy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var lr,By=h(()=>{"use strict";l();Gy();ze();lr={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Uy,execute:async r=>{let e=r.db,t=r.table;try{let n=await re.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var zy,Hy=h(()=>{"use strict";l();zy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var cr,Ky=h(()=>{"use strict";l();Hy();ze();cr={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:zy,execute:async r=>{let e=r.db;try{let o=await re.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var Jy,Vy=h(()=>{"use strict";l();Jy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to insert into"},data:{type:"object",description:"Key-value pairs of column names and values to insert"}},required:["db","table","data"]}});var pr,Qy=h(()=>{"use strict";l();Vy();ze();pr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:Jy,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 re.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 Xy,Yy=h(()=>{"use strict";l();Xy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to update"},data:{type:"object",description:"Key-value pairs of column names and new values"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","data","where"]}});var mr,Zy=h(()=>{"use strict";l();Yy();ze();mr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:Xy,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 re.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 eb,tb=h(()=>{"use strict";l();eb={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var dr,ob=h(()=>{"use strict";l();tb();ze();dr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:eb,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await re.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 nb,rb=h(()=>{"use strict";l();nb={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to count rows from"},where:{type:"string",description:"Optional WHERE clause condition"}},required:["db","table"]}});var ur,sb=h(()=>{"use strict";l();rb();ze();ur={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:nb,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 re.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 ab={};oe(ab,{dbCountTool:()=>ur,dbDeleteTool:()=>dr,dbInsertTool:()=>pr,dbQueryTool:()=>ar,dbSchemaTool:()=>lr,dbTablesTool:()=>cr,dbToolsProject:()=>ib,dbUpdateTool:()=>mr});var ib,Ii=h(()=>{"use strict";l();Wy();By();Ky();Qy();Zy();ob();sb();ib={manifest:{key:"db",name:"db-tools",displayName:"Database Tools",version:"1.0.0",description:"Stateless database operations enabling the AI to interact with local databases.",author:"Sajeer",tools:["db.query","db.schema","db.tables","db.insert","db.update","db.delete","db.count"],category:"database"},tools:[ar,lr,cr,pr,mr,dr,ur],dependencies:{"better-sqlite3":"^11.3.0"}}});var lb,cb=h(()=>{"use strict";l();lb={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});import{NetlifyAPI as bC}from"netlify";var He,fr=h(()=>{"use strict";l();He=class{static getClient(e){let t=e??process.env.NETLIFY_AUTH_TOKEN;if(!t)throw new Error("NETLIFY_AUTH_TOKEN environment variable is required to use Netlify cloud tools.");return new bC(t)}}});var gr,pb=h(()=>{"use strict";l();cb();fr();S();gr={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:lb,execute:async(r,e)=>{let t=r.siteId,o=r.dir,n=r.message;y(`[cloud.deploy] execute siteId="${t}" dir="${o}" message="${n??"none"}"`);try{let i=await He.getClient(e?.config?.credentials?.netlifyAuthToken).deploy(t,o,{message:n||"Deployed via Toolpack SDK",draft:!1});return JSON.stringify({id:i.deployId,url:i.deploy.url,admin_url:i.deploy.admin_url,state:i.deploy.state},null,2)}catch(s){return`Cloud deployment error: ${s instanceof Error?s.message:String(s)}`}},confirmation:{level:"high",reason:"This will deploy to production (live site).",showArgs:["siteId","dir"]}}});var mb,db=h(()=>{"use strict";l();mb={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},deployId:{type:"string",description:"The specific Deployment ID to check"}},required:["siteId","deployId"]}});var hr,ub=h(()=>{"use strict";l();db();fr();hr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:mb,execute:async(r,e)=>{let t=r.siteId,o=r.deployId;try{let s=await He.getClient(e?.config?.credentials?.netlifyAuthToken).getSiteDeploy({site_id:t,deploy_id:o});return JSON.stringify({id:s.id,state:s.state,error_message:s.error_message,created_at:s.created_at,updated_at:s.updated_at,url:s.url},null,2)}catch(n){return`Cloud status error: ${n instanceof Error?n.message:String(n)}`}}}});var fb,gb=h(()=>{"use strict";l();fb={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},limit:{type:"number",description:"Number of recent deployments to return. Defaults to 5.",default:5}},required:["siteId"]}});var yr,hb=h(()=>{"use strict";l();gb();fr();S();yr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:fb,execute:async(r,e)=>{let t=r.siteId,o=r.limit||5;y(`[cloud.list] execute siteId="${t}" limit=${o}`);try{let s=await He.getClient(e?.config?.credentials?.netlifyAuthToken).listSiteDeploys({site_id:t,page:1,per_page:o});if(!Array.isArray(s))return"Unexpected response format from Netlify API";let i=s.map(a=>({id:a.id,state:a.state,created_at:a.created_at,url:a.url,branch:a.branch,title:a.title}));return JSON.stringify(i,null,2)}catch(n){return`Cloud list error: ${n instanceof Error?n.message:String(n)}`}}}});var bb={};oe(bb,{cloudDeployTool:()=>gr,cloudListTool:()=>yr,cloudStatusTool:()=>hr,cloudToolsProject:()=>yb});var yb,Li=h(()=>{"use strict";l();pb();ub();hb();yb={manifest:{key:"cloud",name:"cloud-tools",displayName:"Cloud Deployment",version:"1.0.0",description:"Cloud deployment operations allowing the AI to publish directories directly to the internet.",author:"Sajeer",tools:["cloud.deploy","cloud.status","cloud.list"],category:"cloud"},tools:[gr,hr,yr],dependencies:{netlify:"^13.1.20"}}});var wb,Tb,xb,vb,Cb,kb=h(()=>{"use strict";l();wb="slack.chat.postMessage",Tb="Post Slack Message",xb="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.",vb="slack",Cb={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 Te(r,e){if(r)return r;let t=e?.slackBotToken??process.env.TOOLPACK_SLACK_BOT_TOKEN;if(t)return t;throw new Error("No Slack token available. Set TOOLPACK_SLACK_BOT_TOKEN or pass token in tool args.")}var lt=h(()=>{"use strict";l()});function wC(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}}async function xe(r,e,t){let o=await fetch(`https://slack.com/api/${r}`,{method:"POST",headers:wC(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 ct=h(()=>{"use strict";l()});async function TC(r,e){let t=String(r.channel),o=String(r.text),n=r.thread_ts?String(r.thread_ts):void 0,s=r.blocks?String(r.blocks):void 0,i=Te(r.token,e?.config?.credentials),a={channel:t,text:o};if(n&&(a.thread_ts=n),s)try{a.blocks=JSON.parse(s)}catch{return"Error: blocks is not valid JSON."}let c=await xe("chat.postMessage",i,a),p=c.ts??"";return`Message posted. channel=${c.channel??t} ts=${p}`}var dn,ji=h(()=>{"use strict";l();kb();lt();ct();dn={name:wb,displayName:Tb,description:xb,parameters:Cb,category:vb,execute:TC}});var Sb,Pb,_b,Rb,$b,Eb=h(()=>{"use strict";l();Sb="slack.chat.postEphemeral",Pb="Post Ephemeral Slack Message",_b="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.",Rb="slack",$b={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 xC(r,e){let t=String(r.channel),o=String(r.user),n=String(r.text),s=r.thread_ts?String(r.thread_ts):void 0,i=Te(r.token,e?.config?.credentials),a={channel:t,user:o,text:n};return s&&(a.thread_ts=s),await xe("chat.postEphemeral",i,a),`Ephemeral message sent to user=${o} in channel=${t}.`}var un,Fi=h(()=>{"use strict";l();Eb();lt();ct();un={name:Sb,displayName:Pb,description:_b,parameters:$b,category:Rb,execute:xC}});var Db,Mb,Ab,Nb,Ob,Ib=h(()=>{"use strict";l();Db="slack.reactions.add",Mb="Add Slack Reaction",Ab="Add an emoji reaction to a Slack message. Useful for acknowledging receipt (\u{1F440} eyes), signalling completion (\u2705 white_check_mark), or flagging issues (\u26A0\uFE0F warning). Requires the reactions:write OAuth scope on the Slack app.",Nb="slack",Ob={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 vC(r,e){let t=String(r.channel),o=String(r.timestamp),n=String(r.name),s=Te(r.token,e?.config?.credentials);try{await xe("reactions.add",s,{channel:t,timestamp:o,name:n})}catch(i){if(i instanceof Error&&i.message.includes("already_reacted"))return`Reaction :${n}: already present on message ts=${o}.`;throw i}return`Reaction :${n}: added to message ts=${o} in channel=${t}.`}var fn,qi=h(()=>{"use strict";l();Ib();lt();ct();fn={name:Db,displayName:Mb,description:Ab,parameters:Ob,category:Nb,execute:vC}});var Lb,jb,Fb,qb,Wb,Ub=h(()=>{"use strict";l();Lb="slack.conversations.history",jb="Get Slack Channel History",Fb="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.",qb="slack",Wb={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 CC(r,e){let t=String(r.channel),o=typeof r.limit=="number"?Math.min(r.limit,100):10,n=Te(r.token,e?.config?.credentials),s={channel:t,limit:o};r.oldest&&(s.oldest=String(r.oldest)),r.latest&&(s.latest=String(r.latest));let a=(await xe("conversations.history",n,s)).messages??[];return a.length===0?"No messages found.":[...a].reverse().map(p=>{let m=p.user?`user:${p.user}`:p.bot_id?`bot:${p.bot_id}`:"unknown",d=p.reply_count?` [thread: ${p.reply_count} replies]`:"",g=(p.text??"").replace(/\n/g," ").slice(0,200);return`[${p.ts}] ${m}${d}: ${g}`}).join(`
319
+ `)}var gn,Wi=h(()=>{"use strict";l();Ub();lt();ct();gn={name:Lb,displayName:jb,description:Fb,parameters:Wb,category:qb,execute:CC}});var Gb,Bb,zb,Hb,Kb,Jb=h(()=>{"use strict";l();Gb="slack.conversations.replies",Bb="Get Slack Thread Replies",zb="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.",Hb="slack",Kb={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 kC(r,e){let t=String(r.channel),o=String(r.ts),n=typeof r.limit=="number"?Math.min(r.limit,100):20,s=Te(r.token,e?.config?.credentials),i={channel:t,ts:o,limit:n};r.oldest&&(i.oldest=String(r.oldest)),r.latest&&(i.latest=String(r.latest));let c=(await xe("conversations.replies",s,i)).messages??[];return c.length===0?"No replies found.":c.map((m,d)=>{let g=m.user?`user:${m.user}`:m.bot_id?`bot:${m.bot_id}`:"unknown",w=d===0?" [parent]":"",b=(m.text??"").replace(/\n/g," ").slice(0,200);return`[${m.ts}] ${g}${w}: ${b}`}).join(`
320
+ `)}var hn,Ui=h(()=>{"use strict";l();Jb();lt();ct();hn={name:Gb,displayName:Bb,description:zb,parameters:Kb,category:Hb,execute:kC}});var Vb,Qb,Xb,Yb,Zb,ew=h(()=>{"use strict";l();Vb="slack.auth.test",Qb="Slack Auth Test",Xb="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.",Yb="slack",Zb={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function SC(r,e){let t=Te(r.token,e?.config?.credentials),o=await xe("auth.test",t,{});return JSON.stringify({bot_id:o.bot_id,user_id:o.user_id,user:o.user,team:o.team,team_id:o.team_id,url:o.url},null,2)}var yn,Gi=h(()=>{"use strict";l();ew();lt();ct();yn={name:Vb,displayName:Qb,description:Xb,parameters:Zb,category:Yb,execute:SC}});var ow={};oe(ow,{slackAuthTestTool:()=>yn,slackChatPostEphemeralTool:()=>un,slackChatPostMessageTool:()=>dn,slackConversationsHistoryTool:()=>gn,slackConversationsRepliesTool:()=>hn,slackReactionsAddTool:()=>fn,slackToolsProject:()=>tw});var tw,Bi=h(()=>{"use strict";l();ji();Fi();qi();Wi();Ui();Gi();ji();Fi();qi();Wi();Ui();Gi();tw={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:[dn,un,fn,gn,hn,yn]}});import{execFileSync as PC}from"child_process";function A(r,e){if(r.includes("\0")||r.includes(`
321
+ `)||r.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return r}function _C(r){let e=typeof r.stdout=="string"?r.stdout:"",t=typeof r.stderr=="string"?r.stderr:"",o=r.status??"unknown",n=t.split(/\r?\n/).filter(i=>i.trim().length>0),s=n.find(i=>i.toLowerCase().startsWith("error:"))||n[0]||r.message||"";return`kubectl failed (exit code ${o})${s?`: ${s.trim()}`:""}
322
322
  STDOUT:
323
323
  ${e}
324
324
  STDERR:
325
- ${t}`}function ye(r,e,t=3e4){r.forEach((o,n)=>I(o,`kubectl argument #${n}`)),y(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return LC("kubectl",r,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return FC(o)}}function qC(r){if(!r)return 3e5;let e=r.trim().toLowerCase(),t=/^([0-9]+)(s|m|h)?$/.exec(e);if(!t)return 3e5;let o=Number(t[1]);switch(t[2]){case"h":return o*60*60*1e3;case"m":return o*60*1e3;default:return o*1e3}}function fw(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])=>`${I(t,"label key")}=${I(o,"label value")}`).join(",")}var _e,Pr,_r,Rr,$r,Er,Dr,Mr,Ar,Nr,Or,Ir,gw=h(()=>{"use strict";c();S();_e="kubernetes";Pr={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:_e,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter pods."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter pods.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the pod list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"If true, list pods across all namespaces.",default:!1}},required:[]},execute:async r=>{let e=["get","pods"],t=r.output;t?e.push("-o",t):e.push("-o","wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",I(r.namespace,"namespace"));let o=fw(r.labelSelector)??r.labels;return o&&e.push("-l",I(o,"labels")),ye(e)}},_r={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:_e,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to describe, such as pod, service, deployment."},name:{type:"string",description:"Resource name. Optional for cluster-wide descriptions."},namespace:{type:"string",description:"Namespace containing the resource."}},required:["resource"]},execute:async r=>{let t=["describe",I(r.resource,"resource")];return r.name&&t.push(I(r.name,"name")),r.namespace&&t.push("-n",I(r.namespace,"namespace")),ye(t)}},Rr={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:_e,parameters:{type:"object",properties:{podName:{type:"string",description:"The name of the pod to fetch logs from."},namespace:{type:"string",description:"Namespace of the pod."},container:{type:"string",description:"Container name inside the pod."},tailLines:{type:"number",description:"Number of log lines to show from the end.",default:100},since:{type:"string",description:"Return logs newer than a relative duration like 5m or 1h."}},required:["podName"]},execute:async r=>{let e=["logs",I(r.podName,"podName")];return r.container&&e.push("-c",I(r.container,"container")),r.namespace&&e.push("-n",I(r.namespace,"namespace")),typeof r.tailLines=="number"&&e.push("--tail",`${r.tailLines}`),r.since&&e.push("--since",I(r.since,"since")),ye(e)}},$r={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:_e,parameters:{type:"object",properties:{path:{type:"string",description:"Path to the manifest file to apply."},manifest:{type:"string",description:"Inline YAML manifest to apply if no path is provided."},namespace:{type:"string",description:"Namespace to apply the manifest into, if supported by the manifest."},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without applying changes.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will change cluster state by applying a Kubernetes manifest.",showArgs:["path","namespace"]},execute:async r=>{let e=r.path,t=r.manifest,o=["apply"];if(r.dryRun&&o.push("--dry-run=client"),o.push("-f"),e)return o.push(I(e,"path")),r.namespace&&o.push("-n",I(r.namespace,"namespace")),ye(o);if(!t)throw new Error("Either path or manifest is required to apply a Kubernetes manifest.");return r.namespace&&o.push("-n",I(r.namespace,"namespace")),o.push("-"),ye(o,t)}},Er={name:"k8s.delete_resource",displayName:"Kubernetes Delete Resource",description:"Delete a Kubernetes resource by type and name, or delete resources from a manifest file.",category:_e,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to delete, such as pod, service, deployment."},name:{type:"string",description:"Name of the resource to delete."},namespace:{type:"string",description:"Namespace containing the resource."},path:{type:"string",description:"Path to a manifest file that contains the resources to delete."},force:{type:"boolean",description:"Force deletion of the resource.",default:!1},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without deleting resources.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will delete resources from the Kubernetes cluster.",showArgs:["resource","name","path"]},execute:async r=>{let e=r.path,t=r.resource,o=r.name;if(e){let s=["delete"];return r.dryRun&&s.push("--dry-run=client"),s.push("-f",I(e,"path")),r.namespace&&s.push("-n",I(r.namespace,"namespace")),ye(s)}if(!t||!o)throw new Error("resource and name are required unless a manifest path is provided.");let n=["delete",I(t,"resource"),I(o,"name")];return r.namespace&&n.push("-n",I(r.namespace,"namespace")),r.force&&n.push("--force","--grace-period=0"),r.dryRun&&n.push("--dry-run=client"),ye(n)}},Dr={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:_e,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},output:{type:"string",description:"Output format for the service list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List services across all namespaces.",default:!1}},required:[]},execute:async r=>{let e=["get","services"],t=r.output;return e.push("-o",t||"wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",I(r.namespace,"namespace")),ye(e)}},Mr={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:_e,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter deployments."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter deployments.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the deployment list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List deployments across all namespaces.",default:!1}},required:[]},execute:async r=>{let e=["get","deployments"],t=r.output;e.push("-o",t||"wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",I(r.namespace,"namespace"));let o=fw(r.labelSelector)??r.labels;return o&&e.push("-l",I(o,"labels")),ye(e)}},Ar={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:_e,parameters:{type:"object",properties:{name:{type:"string",description:"ConfigMap name."},namespace:{type:"string",description:"Namespace containing the ConfigMap."},output:{type:"string",description:"Output format, such as yaml or json.",enum:["yaml","json"],default:"yaml"}},required:["name"]},execute:async r=>{let e=["get","configmap",I(r.name,"name"),"-o",r.output||"yaml"];return r.namespace&&e.push("-n",I(r.namespace,"namespace")),ye(e)}},Nr={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:_e,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>ye(["config","use-context",I(r.context,"context")])},Or={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:_e,parameters:{type:"object",properties:{output:{type:"string",description:"Output format for the namespace list.",enum:["wide","name","json","yaml"],default:"wide"}},required:[]},execute:async r=>ye(["get","namespaces","-o",r.output||"wide"])},Ir={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:_e,parameters:{type:"object",properties:{name:{type:"string",description:"Deployment name to wait for."},namespace:{type:"string",description:"Namespace containing the deployment."},timeout:{type:"string",description:"Timeout duration, e.g. 300s or 5m.",default:"300s"}},required:["name"]},execute:async r=>{let e=r.timeout,t=["rollout","status",`deployment/${I(r.name,"name")}`,"--timeout",e||"300s"];return r.namespace&&t.push("-n",I(r.namespace,"namespace")),ye(t,void 0,qC(e))}}});var yw={};ne(yw,{k8sApplyManifestTool:()=>$r,k8sDeleteResourceTool:()=>Er,k8sDescribeTool:()=>_r,k8sGetConfigMapTool:()=>Ar,k8sGetLogsTool:()=>Rr,k8sGetNamespacesTool:()=>Or,k8sListDeploymentsTool:()=>Mr,k8sListPodsTool:()=>Pr,k8sListServicesTool:()=>Dr,k8sSwitchContextTool:()=>Nr,k8sToolsProject:()=>hw,k8sWaitForDeploymentTool:()=>Ir});var hw,Xi=h(()=>{"use strict";c();gw();hw={manifest:{key:"k8s",name:"k8s-tools",displayName:"Kubernetes",version:"1.0.0",description:"Kubernetes command and cluster inspection tools for working with kubectl and manifests.",author:"toolpack-sdk",tools:["k8s.list_pods","k8s.describe","k8s.get_logs","k8s.apply_manifest","k8s.delete_resource","k8s.list_services","k8s.list_deployments","k8s.get_config_map","k8s.switch_context","k8s.get_namespaces","k8s.wait_for_deployment"],category:"kubernetes"},tools:[Pr,_r,Rr,$r,Er,Dr,Mr,Ar,Nr,Or,Ir]}});import{createRemoteJWKSet as tk,jwtVerify as ok}from"jose";function Sw(r){switch(r.mode){case"static":return new sa(r.tokens);case"jwt":return new ia(r);case"custom":return{verifyAccessToken:r.verifyAccessToken}}}async function Pw(r,e,t,o){let n=r.headers.authorization,s=typeof n=="string"&&n.startsWith("Bearer ")?n.slice(7):null;if(!s)return e.writeHead(401,{"WWW-Authenticate":"Bearer"}).end(),!1;let i;try{i=await o.verifyAccessToken(s)}catch{return e.writeHead(401,{"WWW-Authenticate":"Bearer"}).end(),!1}let a="requiredScopes"in t?t.requiredScopes:void 0;if(a?.length){let l=new Set(i.scopes),p=a.filter(m=>!l.has(m));if(p.length>0)return e.writeHead(403).end(`Missing required scopes: ${p.join(", ")}`),!1}return r.auth=i,!0}var sa,ia,_w=h(()=>{"use strict";c();sa=class{tokenSet;constructor(e){if(e.length===0)throw new Error('McpAuthConfig static mode: tokens array must not be empty. Generate a token with: crypto.randomBytes(32).toString("hex")');this.tokenSet=new Set(e)}async verifyAccessToken(e){if(!this.tokenSet.has(e))throw new Error("Invalid bearer token.");return{token:e,clientId:"static-client",scopes:[]}}},ia=class{JWKS;audience;issuer;constructor(e){this.JWKS=tk(new URL(e.jwksUrl)),this.audience=e.audience,this.issuer=e.issuer}async verifyAccessToken(e){let{payload:t}=await ok(e,this.JWKS,{audience:this.audience,issuer:this.issuer}),o=t.scope??t.scp,n=Array.isArray(o)?o.filter(i=>typeof i=="string"):typeof o=="string"?o.split(" ").filter(Boolean):[],s=typeof t.client_id=="string"?t.client_id:typeof t.sub=="string"?t.sub:"unknown";return{token:e,clientId:s,scopes:n,expiresAt:t.exp}}}});var Ew={};ne(Ew,{startMcpServer:()=>pk});import{createServer as nk}from"http";import{randomUUID as rk}from"crypto";import{Server as sk}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as ik}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as ak}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{ListToolsRequestSchema as lk,CallToolRequestSchema as ck}from"@modelcontextprotocol/sdk/types.js";async function pk(r,e,t){let o=new sk({name:e.serverName??"Toolpack SDK",version:e.serverVersion??"2.0.0"},{capabilities:{tools:{}}});if(o.setRequestHandler(lk,async()=>{if(e.searchMode){let i=uk(r,e),a=Ze(),l=i.map(p=>{let m=$w(p);return{name:p.name,description:p.description??"",inputSchema:p.parameters??{type:"object",properties:{}},...m!==void 0&&{annotations:m}}});return{tools:[{name:a.name,description:a.description??"",inputSchema:a.parameters,annotations:{readOnlyHint:!0}},...l,...Rw(e)]}}return{tools:[...aa(r,e.expose).map(i=>{let a=$w(i);return{name:i.name,description:i.description??"",inputSchema:i.parameters??{type:"object",properties:{}},...a!==void 0&&{annotations:a}}}),...Rw(e)]}}),o.setRequestHandler(ck,async n=>{let{name:s,arguments:i}=n.params;if(e.searchMode&&bt(s)){if(!t)return Oe("tool.search is not available: searchFn was not provided to startMcpServer.",!0);try{let l=t(i??{});return Oe(l)}catch(l){let p=l instanceof Error?l.message:String(l);return Oe(`tool.search error: ${p}`,!0)}}if(s.startsWith("agent.")){let l=s.slice(6),p=(e.agents??[]).find(m=>m.name===l);if(!p)return Oe(`Agent not found: ${l}`,!0);try{let m=await p.invoke(i??{});return Oe(m)}catch(m){let d=m instanceof Error?m.message:String(m);return Oe(`Agent error (${l}): ${d}`,!0)}}let a=mk(r,s,e.expose);if(!a)return Oe(`Tool not found: ${s}`,!0);try{let l={workspaceRoot:process.cwd(),config:r.getConfig().additionalConfigurations??{},log:m=>P(`[MCP Tool] ${m}`)},p=await a.execute(i??{},l);return Oe(p)}catch(l){let p=l instanceof Error?l.message:String(l);return Oe(`Error executing ${s}: ${p}`,!0)}}),e.transport==="stdio"){let n=new ik;return await o.connect(n),{get toolCount(){return aa(r,e.expose).length},port:0,stop:async()=>{await o.close()}}}if(e.transport==="http"){let n=e.port??3e3;e.auth||P("[MCP Server] Warning: HTTP transport started without authentication. Safe for localhost only. Set `auth` in startMcpServer() before exposing this server to a network.");let s=new ak({sessionIdGenerator:()=>rk()}),i=e.auth?Sw(e.auth):null,a=nk(async(p,m)=>{if(e.auth?.mode==="jwt"&&e.serverUrl&&p.url==="/.well-known/oauth-protected-resource"){let d={resource:e.serverUrl};e.auth.issuer&&(d.authorization_servers=[e.auth.issuer]),m.writeHead(200,{"Content-Type":"application/json"}).end(JSON.stringify(d));return}i&&!await Pw(p,m,e.auth,i).catch(g=>(P(`[MCP Server] Auth error: ${g instanceof Error?g.message:String(g)}`),m.headersSent||m.writeHead(500).end("Internal Server Error"),!1))||s.handleRequest(p,m).catch(d=>{P(`[MCP Server] HTTP request handler error: ${d instanceof Error?d.message:String(d)}`),m.headersSent||m.writeHead(500).end("Internal Server Error")})});await o.connect(s);try{await new Promise((p,m)=>{let d=g=>{m(g.code==="EADDRINUSE"?new Error(`MCP HTTP server failed to start: port ${n} is already in use.`):g)};a.once("error",d),a.listen(n,()=>{a.off("error",d),p()})})}catch(p){throw await o.close().catch(()=>{}),p}let l=a.address().port;return{get toolCount(){return aa(r,e.expose).length},port:l,stop:async()=>{try{await o.close()}finally{await new Promise((p,m)=>{a.close(d=>d?m(d):p())})}}}}throw new Error(`Unknown MCP transport: "${e.transport}". Use 'stdio' or 'http'.`)}function aa(r,e){return e?e.categories?.length?r.getByCategories(e.categories):e.tools?.length?r.getByNames(e.tools):r.getEnabled():r.getEnabled()}function mk(r,e,t){let o=r.get(e);if(o)return t?.categories?.length?new Set(t.categories).has(o.category)?o:void 0:t?.tools?.length?t.tools.includes(e)?o:void 0:dk(r,o,e)?o:void 0}function dk(r,e,t){let{enabledTools:o,enabledToolCategories:n}=r.getConfig();return o.length===0&&n.length===0?!0:o.includes(t)||n.includes(e.category)}function Rw(r){return(r.agents??[]).map(e=>({name:`agent.${e.name}`,description:e.description,inputSchema:e.inputSchema??{type:"object",properties:{}}}))}function uk(r,e){let t=r.getConfig().toolSearch;if(!t)return[];let o=r.getByNames(t.alwaysLoadedTools),n=r.getByCategories(t.alwaysLoadedCategories),s=new Set([Ye]),i=[...o,...n].filter(a=>s.has(a.name)?!1:(s.add(a.name),!0));if(e.expose?.categories?.length){let a=new Set(e.expose.categories);return i.filter(l=>a.has(l.category))}if(e.expose?.tools?.length){let a=new Set(e.expose.tools);return i.filter(l=>a.has(l.name))}return i}function $w(r){if(r.annotations)return r.annotations;if(r.confirmation)return{destructiveHint:!0}}function Oe(r,e=!1){return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r,null,2)}],isError:e}}var Dw=h(()=>{"use strict";c();S();_w();Gt()});c();se();c();se();import{EventEmitter as hT}from"events";c();se();async function ba(r,e={}){let{maxRetries:t=3,backoffMs:o=[1e4,3e4,6e4],isRetryable:n=i=>i instanceof re,onRetry:s}=e;for(let i=0;i<=t;i++)try{return await r()}catch(a){if(n(a)&&i<t){let l=a?.retryAfter!=null?a.retryAfter*1e3:o[i]??o[o.length-1]??6e4;s?.(i+1,l,a),await new Promise(p=>setTimeout(p,l));continue}throw a}throw new re("Rate limit retries exhausted")}c();se();var qt=class extends j{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`
325
+ ${t}`}function ye(r,e,t=3e4){r.forEach((o,n)=>A(o,`kubectl argument #${n}`)),y(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return PC("kubectl",r,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return _C(o)}}function RC(r){if(!r)return 3e5;let e=r.trim().toLowerCase(),t=/^([0-9]+)(s|m|h)?$/.exec(e);if(!t)return 3e5;let o=Number(t[1]);switch(t[2]){case"h":return o*60*60*1e3;case"m":return o*60*1e3;default:return o*1e3}}function nw(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 Pe,br,wr,Tr,xr,vr,Cr,kr,Sr,Pr,_r,Rr,rw=h(()=>{"use strict";l();S();Pe="kubernetes";br={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:Pe,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=nw(r.labelSelector)??r.labels;return o&&e.push("-l",A(o,"labels")),ye(e)}},wr={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:Pe,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")),ye(t)}},Tr={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:Pe,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")),ye(e)}},xr={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:Pe,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")),ye(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("-"),ye(o,t)}},vr={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:Pe,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")),ye(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"),ye(n)}},Cr={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:Pe,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")),ye(e)}},kr={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:Pe,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=nw(r.labelSelector)??r.labels;return o&&e.push("-l",A(o,"labels")),ye(e)}},Sr={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:Pe,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")),ye(e)}},Pr={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:Pe,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>ye(["config","use-context",A(r.context,"context")])},_r={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:Pe,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=>ye(["get","namespaces","-o",r.output||"wide"])},Rr={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:Pe,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")),ye(t,void 0,RC(e))}}});var iw={};oe(iw,{k8sApplyManifestTool:()=>xr,k8sDeleteResourceTool:()=>vr,k8sDescribeTool:()=>wr,k8sGetConfigMapTool:()=>Sr,k8sGetLogsTool:()=>Tr,k8sGetNamespacesTool:()=>_r,k8sListDeploymentsTool:()=>kr,k8sListPodsTool:()=>br,k8sListServicesTool:()=>Cr,k8sSwitchContextTool:()=>Pr,k8sToolsProject:()=>sw,k8sWaitForDeploymentTool:()=>Rr});var sw,zi=h(()=>{"use strict";l();rw();sw={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:[br,wr,Tr,xr,vr,Cr,kr,Sr,Pr,_r,Rr]}});import{createRemoteJWKSet as HC,jwtVerify as KC}from"jose";function yw(r){switch(r.mode){case"static":return new Zi(r.tokens);case"jwt":return new ea(r);case"custom":return{verifyAccessToken:r.verifyAccessToken}}}async function bw(r,e,t,o){let n=r.headers.authorization,s=typeof n=="string"&&n.startsWith("Bearer ")?n.slice(7):null;if(!s)return e.writeHead(401,{"WWW-Authenticate":"Bearer"}).end(),!1;let i;try{i=await o.verifyAccessToken(s)}catch{return e.writeHead(401,{"WWW-Authenticate":"Bearer"}).end(),!1}let a="requiredScopes"in t?t.requiredScopes:void 0;if(a?.length){let c=new Set(i.scopes),p=a.filter(m=>!c.has(m));if(p.length>0)return e.writeHead(403).end(`Missing required scopes: ${p.join(", ")}`),!1}return r.auth=i,!0}var Zi,ea,ww=h(()=>{"use strict";l();Zi=class{tokenSet;constructor(e){if(e.length===0)throw new Error('McpAuthConfig static mode: tokens array must not be empty. Generate a token with: crypto.randomBytes(32).toString("hex")');this.tokenSet=new Set(e)}async verifyAccessToken(e){if(!this.tokenSet.has(e))throw new Error("Invalid bearer token.");return{token:e,clientId:"static-client",scopes:[]}}},ea=class{JWKS;audience;issuer;constructor(e){this.JWKS=HC(new URL(e.jwksUrl)),this.audience=e.audience,this.issuer=e.issuer}async verifyAccessToken(e){let{payload:t}=await KC(e,this.JWKS,{audience:this.audience,issuer:this.issuer}),o=t.scope??t.scp,n=Array.isArray(o)?o.filter(i=>typeof i=="string"):typeof o=="string"?o.split(" ").filter(Boolean):[],s=typeof t.client_id=="string"?t.client_id:typeof t.sub=="string"?t.sub:"unknown";return{token:e,clientId:s,scopes:n,expiresAt:t.exp}}}});var vw={};oe(vw,{startMcpServer:()=>tk});import{createServer as JC}from"http";import{randomUUID as VC}from"crypto";import{Server as QC}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as XC}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as YC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{ListToolsRequestSchema as ZC,CallToolRequestSchema as ek}from"@modelcontextprotocol/sdk/types.js";async function tk(r,e,t){let o=new QC({name:e.serverName??"Toolpack SDK",version:e.serverVersion??"2.0.0"},{capabilities:{tools:{}}});if(o.setRequestHandler(ZC,async()=>{if(e.searchMode){let i=rk(r,e),a=Ye(),c=i.map(p=>{let m=xw(p);return{name:p.name,description:p.description??"",inputSchema:p.parameters??{type:"object",properties:{}},...m!==void 0&&{annotations:m}}});return{tools:[{name:a.name,description:a.description??"",inputSchema:a.parameters,annotations:{readOnlyHint:!0}},...c,...Tw(e)]}}return{tools:[...ta(r,e.expose).map(i=>{let a=xw(i);return{name:i.name,description:i.description??"",inputSchema:i.parameters??{type:"object",properties:{}},...a!==void 0&&{annotations:a}}}),...Tw(e)]}}),o.setRequestHandler(ek,async n=>{let{name:s,arguments:i}=n.params;if(e.searchMode&&bt(s)){if(!t)return Ie("tool.search is not available: searchFn was not provided to startMcpServer.",!0);try{let c=t(i??{});return Ie(c)}catch(c){let p=c instanceof Error?c.message:String(c);return Ie(`tool.search error: ${p}`,!0)}}if(s.startsWith("agent.")){let c=s.slice(6),p=(e.agents??[]).find(m=>m.name===c);if(!p)return Ie(`Agent not found: ${c}`,!0);try{let m=await p.invoke(i??{});return Ie(m)}catch(m){let d=m instanceof Error?m.message:String(m);return Ie(`Agent error (${c}): ${d}`,!0)}}let a=ok(r,s,e.expose);if(!a)return Ie(`Tool not found: ${s}`,!0);try{let c={workspaceRoot:process.cwd(),config:r.getConfig().additionalConfigurations??{},log:m=>P(`[MCP Tool] ${m}`),processRegistry:r.runtimeContext?.processRegistry,githubTokenStore:r.runtimeContext?.githubTokenStore},p=await a.execute(i??{},c);return Ie(p)}catch(c){let p=c instanceof Error?c.message:String(c);return Ie(`Error executing ${s}: ${p}`,!0)}}),e.transport==="stdio"){let n=new XC;return await o.connect(n),{get toolCount(){return ta(r,e.expose).length},port:0,stop:async()=>{await o.close()}}}if(e.transport==="http"){let n=e.port??3e3;e.auth||P("[MCP Server] Warning: HTTP transport started without authentication. Safe for localhost only. Set `auth` in startMcpServer() before exposing this server to a network.");let s=new YC({sessionIdGenerator:()=>VC()}),i=e.auth?yw(e.auth):null,a=JC(async(p,m)=>{if(e.auth?.mode==="jwt"&&e.serverUrl&&p.url==="/.well-known/oauth-protected-resource"){let d={resource:e.serverUrl};e.auth.issuer&&(d.authorization_servers=[e.auth.issuer]),m.writeHead(200,{"Content-Type":"application/json"}).end(JSON.stringify(d));return}i&&!await bw(p,m,e.auth,i).catch(g=>(P(`[MCP Server] Auth error: ${g instanceof Error?g.message:String(g)}`),m.headersSent||m.writeHead(500).end("Internal Server Error"),!1))||s.handleRequest(p,m).catch(d=>{P(`[MCP Server] HTTP request handler error: ${d instanceof Error?d.message:String(d)}`),m.headersSent||m.writeHead(500).end("Internal Server Error")})});await o.connect(s);try{await new Promise((p,m)=>{let d=g=>{m(g.code==="EADDRINUSE"?new Error(`MCP HTTP server failed to start: port ${n} is already in use.`):g)};a.once("error",d),a.listen(n,()=>{a.off("error",d),p()})})}catch(p){throw await o.close().catch(()=>{}),p}let c=a.address().port;return{get toolCount(){return ta(r,e.expose).length},port:c,stop:async()=>{try{await o.close()}finally{await new Promise((p,m)=>{a.close(d=>d?m(d):p())})}}}}throw new Error(`Unknown MCP transport: "${e.transport}". Use 'stdio' or 'http'.`)}function ta(r,e){return e?e.categories?.length?r.getByCategories(e.categories):e.tools?.length?r.getByNames(e.tools):r.getEnabled():r.getEnabled()}function ok(r,e,t){let o=r.get(e);if(o)return t?.categories?.length?new Set(t.categories).has(o.category)?o:void 0:t?.tools?.length?t.tools.includes(e)?o:void 0:nk(r,o,e)?o:void 0}function nk(r,e,t){let{enabledTools:o,enabledToolCategories:n}=r.getConfig();return o.length===0&&n.length===0?!0:o.includes(t)||n.includes(e.category)}function Tw(r){return(r.agents??[]).map(e=>({name:`agent.${e.name}`,description:e.description,inputSchema:e.inputSchema??{type:"object",properties:{}}}))}function rk(r,e){let t=r.getConfig().toolSearch;if(!t)return[];let o=r.getByNames(t.alwaysLoadedTools),n=r.getByCategories(t.alwaysLoadedCategories),s=new Set([Xe]),i=[...o,...n].filter(a=>s.has(a.name)?!1:(s.add(a.name),!0));if(e.expose?.categories?.length){let a=new Set(e.expose.categories);return i.filter(c=>a.has(c.category))}if(e.expose?.tools?.length){let a=new Set(e.expose.tools);return i.filter(c=>a.has(c.name))}return i}function xw(r){if(r.annotations)return r.annotations;if(r.confirmation)return{destructiveHint:!0}}function Ie(r,e=!1){return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r,null,2)}],isError:e}}var Cw=h(()=>{"use strict";l();S();ww();Wt()});l();ae();l();ae();import{EventEmitter as cT}from"events";l();ae();async function da(r,e={}){let{maxRetries:t=3,backoffMs:o=[1e4,3e4,6e4],isRetryable:n=i=>i instanceof ie,onRetry:s}=e;for(let i=0;i<=t;i++)try{return await r()}catch(a){if(n(a)&&i<t){let c=a?.retryAfter!=null?a.retryAfter*1e3:o[i]??o[o.length-1]??6e4;s?.(i+1,c,a),await new Promise(p=>setTimeout(p,c));continue}throw a}throw new ie("Rate limit retries exhausted")}l();ae();var jt=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`
326
326
  Context Window Exceeded
327
327
  =======================
328
328
  Conversation ID: ${this.conversationId}
@@ -333,7 +333,7 @@ Usage: ${this.getUsagePercentage()}%
333
333
  Strategy: ${this.strategy}
334
334
 
335
335
  Message: ${this.message}
336
- `.trim()}};var Wt=class extends j{constructor(t,o,n,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=n;this.failureReason=s;this.summaryAttempt=i;this.name="SummarizationError"}conversationId;messageCount;failureReason;summaryAttempt;isRetryable(){return this.failureReason==="provider_error"||this.failureReason==="insufficient_tokens"}getSuggestedRecovery(){switch(this.failureReason){case"provider_error":return"Retry the summarization request or switch to a different summarizer model";case"invalid_response":return"Review the summarizer prompt or use a different model";case"insufficient_tokens":return"Reduce the number of messages to summarize or increase the summary token budget";case"invalid_quality":return"Adjust summarization parameters or use a more capable model";default:return"Manual intervention required"}}getDetailedReport(){let t=`
336
+ `.trim()}};var Ft=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=`
337
337
  Summarization Error
338
338
  ===================
339
339
  Conversation ID: ${this.conversationId}
@@ -345,11 +345,11 @@ Recovery Action: ${this.getSuggestedRecovery()}
345
345
  Message: ${this.message}`;return this.summaryAttempt?t+`
346
346
 
347
347
  Partial Summary:
348
- ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}};c();var Qr=null;async function Vw(){if(!Qr)try{Qr=await import("js-tiktoken")}catch{}return Qr}var wa={"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},Qw=2;async function Xw(r,e){try{let t=await Vw();if(!t)return je(r);let o=t.encoding_for_model(e),n=0,s=wa[e]??wa.__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+=Qw,n}catch{return je(r)}}async function Yw(r,e){try{let t=je(r);return Math.ceil(t*1.1)}catch{return je(r)}}async function Zw(r,e){try{let t=je(r);return Math.ceil(t*1.05)}catch{return je(r)}}async function eT(r,e){let t=je(r);return Math.ceil(t*1.05)}function je(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 Ta(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?Xw(r,e):o==="anthropic"||o==="claude"?Yw(r,e):o==="gemini"||o==="google"?Zw(r,e):o==="ollama"?eT(r,e):je(r)}function Ik(r,e,t){let o=e-t;return r>o}function jk(r,e){return Math.round(r/e*100)}function xa(r,e=1.15){return Math.ceil(r*e)}c();function va(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=Xr(p);if(s+=m,n.push(p),p.role==="assistant"&&p.tool_calls?.length){let d=new Set(p.tool_calls.map(g=>g.id));for(let g of r)g.role==="tool"&&g.tool_call_id&&d.has(g.tool_call_id)&&(s+=Xr(g),n.push(g))}}let a=new Set(n),l=r.filter(p=>!a.has(p));return{removed:n.length,tokensReclaimed:s,newTotal:l.length,pruneInfo:{beforeCount:o,afterCount:l.length,removedMessages:n}}}function qk(r,e){if(typeof r.content=="string"){let t=e*4;if(r.content.length<=t)return r;let o=r.content.substring(0,t),n=Math.ceil((r.content.length-t)/4);return{...r,content:`${o}
348
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}};l();var Gr=null;async function Ww(){if(!Gr)try{Gr=await import("js-tiktoken")}catch{}return Gr}var ua={"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},Uw=2;async function Gw(r,e){try{let t=await Ww();if(!t)return je(r);let o=t.encoding_for_model(e),n=0,s=ua[e]??ua.__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+=Uw,n}catch{return je(r)}}async function Bw(r,e){try{let t=je(r);return Math.ceil(t*1.1)}catch{return je(r)}}async function zw(r,e){try{let t=je(r);return Math.ceil(t*1.05)}catch{return je(r)}}async function Hw(r,e){let t=je(r);return Math.ceil(t*1.05)}function je(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 fa(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?Gw(r,e):o==="anthropic"||o==="claude"?Bw(r,e):o==="gemini"||o==="google"?zw(r,e):o==="ollama"?Hw(r,e):je(r)}function _k(r,e,t){let o=e-t;return r>o}function Rk(r,e){return Math.round(r/e*100)}function ga(r,e=1.15){return Math.ceil(r*e)}l();function ha(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=Br(p);if(s+=m,n.push(p),p.role==="assistant"&&p.tool_calls?.length){let d=new Set(p.tool_calls.map(g=>g.id));for(let g of r)g.role==="tool"&&g.tool_call_id&&d.has(g.tool_call_id)&&(s+=Br(g),n.push(g))}}let a=new Set(n),c=r.filter(p=>!a.has(p));return{removed:n.length,tokensReclaimed:s,newTotal:c.length,pruneInfo:{beforeCount:o,afterCount:c.length,removedMessages:n}}}function Dk(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}
349
349
 
350
- [...truncated ${n} tokens]`}}else if(Array.isArray(r.content)){let t=r.content.filter(a=>a.type==="text"),o=t.reduce((a,l)=>a+(l.text?.length||0),0),n=e*4;if(o<=n)return r;let s=0,i=[];for(let a of t)if(a.type==="text"){let l=n-s;if(l<=0)break;let p=a.text;if(p.length<=l)i.push(a),s+=p.length;else{let m=p.substring(0,l),d=Math.ceil((p.length-l)/4);i.push({type:"text",text:`${m}
350
+ [...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),d=Math.ceil((p.length-c)/4);i.push({type:"text",text:`${m}
351
351
 
352
- [...truncated ${d} tokens]`});break}}return{...r,content:i.length>0?i:r.content}}return r}function Xr(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 Wk(r){let e={system:[],user:[],assistant:[],tool:[]};return r.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function Uk(r){let e=0,t={},o=0;for(let n of r){let s=Xr(n);e+=s,o=Math.max(o,s),t[n.role]??=0,t[n.role]++}return{totalMessages:r.length,totalTokens:e,byRole:t,largestMessageTokens:o}}c();se();function Yr(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 tT(r,e){if(e)return e;let t=r.filter(l=>l.role==="user"),o=r.filter(l=>l.role==="assistant"),n=r.filter(l=>l.role==="tool"),s=r.length,i=t.length,a=o.length;return`Please provide a concise summary of the following conversation history. The conversation contains ${s} messages (${i} user messages, ${a} assistant responses${n.length>0?`, and ${n.length} tool responses`:""}).
352
+ [...truncated ${d} tokens]`});break}}return{...r,content:i.length>0?i:r.content}}return r}function Br(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 Mk(r){let e={system:[],user:[],assistant:[],tool:[]};return r.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function Ak(r){let e=0,t={},o=0;for(let n of r){let s=Br(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();ae();function zr(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 Kw(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`:""}).
353
353
 
354
354
  Focus on:
355
355
  1. Key topics discussed
@@ -361,22 +361,22 @@ The summary should be comprehensive yet concise, preserving all critical informa
361
361
 
362
362
  ---
363
363
  CONVERSATION:
364
- ${r.map((l,p)=>{let m=Yr(l);return`[Message ${p+1}] ${l.role.toUpperCase()}: ${m.substring(0,200)}${m.length>200?"...":""}`}).join(`
364
+ ${r.map((c,p)=>{let m=zr(c);return`[Message ${p+1}] ${c.role.toUpperCase()}: ${m.substring(0,200)}${m.length>200?"...":""}`}).join(`
365
365
  `)}
366
366
  ---
367
367
 
368
- SUMMARY:`}function Zr(r,e){return{role:"system",content:`[Context Summary]
368
+ SUMMARY:`}function Hr(r,e){return{role:"system",content:`[Context Summary]
369
369
  This conversation has been summarized to manage context window. The following is a summary of the first ${e} messages:
370
370
 
371
371
  ${r}
372
372
 
373
373
  [End Summary]
374
374
 
375
- Use this summary to understand the conversation context. When responding, acknowledge that you're aware of the previous conversation and continue naturally.`}}function Hk(r){let e=new Set,t=[],o=[],n="";for(let s of r)if(s.role==="user"){let i=Yr(s);n=i,i.includes("?")&&o.push(i.split(`
376
- `)[0]);let a=i.match(/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b/g);a&&a.forEach(l=>e.add(l))}else if(s.role==="assistant"){let i=Yr(s);if(i.includes("decided")||i.includes("concluded")||i.includes("determined")){let a=i.split(/[.!?]+/);for(let l of a)(l.includes("decided")||l.includes("concluded")||l.includes("determined"))&&t.push(l.trim())}}return{topics:Array.from(e).slice(0,10),decisions:t.slice(0,5),userGoals:o.slice(0,5),context:n.substring(0,200)}}function oT(r){return Math.ceil(r.length/4)}function Ca(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 ka(r,e){let t=tT(r,e.summaryPrompt);return[{role:"system",content:`You are a conversation summarizer. Your task is to create a clear, concise summary of the provided conversation that preserves all critical information.
375
+ Use this summary to understand the conversation context. When responding, acknowledge that you're aware of the previous conversation and continue naturally.`}}function Lk(r){let e=new Set,t=[],o=[],n="";for(let s of r)if(s.role==="user"){let i=zr(s);n=i,i.includes("?")&&o.push(i.split(`
376
+ `)[0]);let a=i.match(/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b/g);a&&a.forEach(c=>e.add(c))}else if(s.role==="assistant"){let i=zr(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 Jw(r){return Math.ceil(r.length/4)}function ya(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 ba(r,e){let t=Kw(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.
377
377
 
378
378
  Maximum summary length: ${e.maxSummaryTokens||500} tokens.
379
- Format: Write only the summary without any additional commentary.`},{role:"user",content:t}]}function Sa(r,e,t){let o=oT(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function Kk(r,e,t){let o=[...r];return o.push(Zr(e.summary,e.messageCount)),o.push(...t),o}function Jk(r,e,t){let o=Math.round(r.tokensSaved/r.originalTokens*100);return`
379
+ Format: Write only the summary without any additional commentary.`},{role:"user",content:t}]}function wa(r,e,t){let o=Jw(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function jk(r,e,t){let o=[...r];return o.push(Hr(e.summary,e.messageCount)),o.push(...t),o}function Fk(r,e,t){let o=Math.round(r.tokensSaved/r.originalTokens*100);return`
380
380
  Summarization Report
381
381
  ====================
382
382
  Timestamp: ${r.timestamp.toISOString()}
@@ -395,39 +395,39 @@ Message Count:
395
395
 
396
396
  Summary Preview:
397
397
  ${r.summary.substring(0,300)}${r.summary.length>300?"...":""}
398
- `.trim()}function Vk(r){if(r.length===0)throw new j("Cannot merge empty summarization results","CONTEXT_WINDOW_ERROR");return{summary:r.map(t=>`[Round ${r.indexOf(t)+1}] ${t.summary}`).join(`
398
+ `.trim()}function qk(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(`
399
399
 
400
- `),messageCount:r.reduce((t,o)=>t+o.messageCount,0),originalTokens:r.reduce((t,o)=>t+o.originalTokens,0),summaryTokens:r.reduce((t,o)=>t+o.summaryTokens,0),tokensSaved:r.reduce((t,o)=>t+o.tokensSaved,0),timestamp:new Date}}c();var es=class{states=new Map;config;maxTokens=1e5;constructor(e){this.config=e}getOrCreateState(e){return this.states.has(e)||this.states.set(e,{conversationId:e,estimatedTokens:0,lastUpdated:Date.now(),pruneCount:0,lastPrunedAt:void 0,warningsSent:0,summarizationCount:0}),this.states.get(e)}updateTokenCount(e,t){let o=this.getOrCreateState(e);return o.estimatedTokens=t,o.lastUpdated=Date.now(),o}recordPruneOperation(e,t){let o=this.getOrCreateState(e);return o.pruneCount++,o.lastPrunedAt=Date.now(),o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}recordWarning(e){let t=this.getOrCreateState(e);return t.warningsSent++,t.lastUpdated=Date.now(),t}recordSummarization(e,t){let o=this.getOrCreateState(e);return o.summarizationCount++,o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}getState(e){return this.states.get(e)}getAllStates(){return Array.from(this.states.values())}deleteState(e){return this.states.delete(e)}clearAllStates(){this.states.clear()}getStatistics(e){let t=this.states.get(e);if(!t)return null;let o=this.config.pruneThreshold||1e5,n=Math.round(t.estimatedTokens/o*100);return{conversationId:e,currentTokens:t.estimatedTokens,pruneCount:t.pruneCount,summarizationCount:t.summarizationCount,warningsSent:t.warningsSent,lastActivity:new Date(t.lastUpdated),contextWindowPercentage:n}}getExceedingThreshold(e){let t=e||this.maxTokens*(this.config.pruneThreshold||85)/100;return Array.from(this.states.values()).filter(o=>o.estimatedTokens>t)}getAtRiskConversations(e=80){let t=this.maxTokens,o=t*e/100;return Array.from(this.states.values()).filter(n=>n.estimatedTokens>o&&n.estimatedTokens<=t)}generateReport(){let e=this.getAllStates();if(e.length===0)return"No conversations tracked yet.";let t=this.config.pruneThreshold||1e5,o=["Context Window State Report","==========================",`Report Generated: ${new Date().toISOString()}`,`Context Window Limit: ${t} tokens`,`Total Conversations: ${e.length}`,""],n=e.reduce((d,g)=>d+g.estimatedTokens,0),s=e.reduce((d,g)=>d+g.pruneCount,0),i=e.reduce((d,g)=>d+g.summarizationCount,0),a=Math.round(n/e.length);o.push("Summary:"),o.push(`- Total tokens across all conversations: ${n}`),o.push(`- Average tokens per conversation: ${a}`),o.push(`- Total prune operations: ${s}`),o.push(`- Total summarizations: ${i}`),o.push("");let l=this.getAtRiskConversations();l.length>0&&(o.push(`At-Risk Conversations (80%+ threshold): ${l.length}`),l.forEach(d=>{let g=Math.round(d.estimatedTokens/t*100);o.push(`- ${d.conversationId}: ${d.estimatedTokens}/${t} tokens (${g}%)`)}),o.push(""));let p=this.getExceedingThreshold();return p.length>0&&(o.push(`Exceeded Conversations: ${p.length}`),p.forEach(d=>{let g=d.estimatedTokens-t;o.push(`- ${d.conversationId}: ${d.estimatedTokens}/${t} tokens (+${g} over)`)}),o.push("")),o.push("Most Active Conversations (by operations):"),[...e].sort((d,g)=>{let b=d.pruneCount+d.summarizationCount;return g.pruneCount+g.summarizationCount-b}).slice(0,5).forEach(d=>{let g=d.pruneCount+d.summarizationCount;o.push(`- ${d.conversationId}: ${d.pruneCount} prunes, ${d.summarizationCount} summarizations (${g} operations)`)}),o.join(`
401
- `)}export(){let e={};for(let[t,o]of this.states.entries())e[t]={...o,lastUpdated:o.lastUpdated,lastPrunedAt:o.lastPrunedAt};return e}import(e){for(let[t,o]of Object.entries(e))this.states.set(t,{...o,lastUpdated:typeof o.lastUpdated=="number"?o.lastUpdated:new Date(o.lastUpdated).getTime(),lastPrunedAt:o.lastPrunedAt&&typeof o.lastPrunedAt!="number"?new Date(o.lastPrunedAt).getTime():o.lastPrunedAt})}pruneInactiveConversations(e=60){let t=Date.now()-e*60*1e3,o=[];for(let[n,s]of this.states.entries())s.lastUpdated<t&&o.push(n);return o.forEach(n=>this.states.delete(n)),o}getMemoryUsage(){let e=this.states.size,t=e*500;return{conversationCount:e,approximateByteSize:t}}validateIntegrity(){let e=[];for(let[t,o]of this.states.entries())(!t||typeof t!="string")&&e.push(`Invalid conversation ID: ${t}`),o.estimatedTokens<0&&e.push(`Negative token count for ${t}: ${o.estimatedTokens}`),o.pruneCount<0&&e.push(`Negative prune count for ${t}: ${o.pruneCount}`),o.summarizationCount<0&&e.push(`Negative summarization count for ${t}: ${o.summarizationCount}`),o.warningsSent<0&&e.push(`Negative warning count for ${t}: ${o.warningsSent}`),(typeof o.lastUpdated!="number"||o.lastUpdated<=0)&&e.push(`Invalid lastUpdated timestamp for ${t}`),o.lastPrunedAt!==void 0&&(typeof o.lastPrunedAt!="number"||o.lastPrunedAt<=0)&&e.push(`Invalid lastPrunedAt timestamp for ${t}`);return{isValid:e.length===0,issues:e}}};function Pa(r){return new es(r)}c();Gt();var Bt=class{discoveryCache=new ht;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(Ze()),s.add(Ye);let i=o.toolSearch?.alwaysLoadedTools??[];for(let l of i){let p=t.get(l);p&&!s.has(l)&&(n.push(this.toSchema(p)),s.add(l))}let a=o.toolSearch?.alwaysLoadedCategories??[];for(let l of a)for(let p of t.getByCategory(l))s.has(p.name)||(n.push(this.toSchema(p)),s.add(p.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let l=ht.fromMessages(e);this.discoveryCache.merge(l);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let d=t.get(m);d&&!s.has(m)&&d.cacheable!==!1&&(n.push(this.toSchema(d)),s.add(m))}}return n}resolveLegacy(e,t){let o;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)o=e.getEnabled();else{let n=e.getByNames(t.enabledTools),s=e.getByCategories(t.enabledToolCategories),i=new Set;o=[];for(let a of[...n,...s])i.has(a.name)||(i.add(a.name),o.push(a))}return o.map(n=>this.toSchema(n))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};zt();Gt();c();function Da(r){if(r.disabled)return"";let e=r.includeWorkingDirectory!==!1,t=r.includeToolCategories!==!1,o=e?`
400
+ `),messageCount:r.reduce((t,o)=>t+o.messageCount,0),originalTokens:r.reduce((t,o)=>t+o.originalTokens,0),summaryTokens:r.reduce((t,o)=>t+o.summaryTokens,0),tokensSaved:r.reduce((t,o)=>t+o.tokensSaved,0),timestamp:new Date}}l();var Kr=class{states=new Map;config;maxTokens=1e5;constructor(e){this.config=e}getOrCreateState(e){return this.states.has(e)||this.states.set(e,{conversationId:e,estimatedTokens:0,lastUpdated:Date.now(),pruneCount:0,lastPrunedAt:void 0,warningsSent:0,summarizationCount:0}),this.states.get(e)}updateTokenCount(e,t){let o=this.getOrCreateState(e);return o.estimatedTokens=t,o.lastUpdated=Date.now(),o}recordPruneOperation(e,t){let o=this.getOrCreateState(e);return o.pruneCount++,o.lastPrunedAt=Date.now(),o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}recordWarning(e){let t=this.getOrCreateState(e);return t.warningsSent++,t.lastUpdated=Date.now(),t}recordSummarization(e,t){let o=this.getOrCreateState(e);return o.summarizationCount++,o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}getState(e){return this.states.get(e)}getAllStates(){return Array.from(this.states.values())}deleteState(e){return this.states.delete(e)}clearAllStates(){this.states.clear()}getStatistics(e){let t=this.states.get(e);if(!t)return null;let o=this.config.pruneThreshold||1e5,n=Math.round(t.estimatedTokens/o*100);return{conversationId:e,currentTokens:t.estimatedTokens,pruneCount:t.pruneCount,summarizationCount:t.summarizationCount,warningsSent:t.warningsSent,lastActivity:new Date(t.lastUpdated),contextWindowPercentage:n}}getExceedingThreshold(e){let t=e||this.maxTokens*(this.config.pruneThreshold||85)/100;return Array.from(this.states.values()).filter(o=>o.estimatedTokens>t)}getAtRiskConversations(e=80){let t=this.maxTokens,o=t*e/100;return Array.from(this.states.values()).filter(n=>n.estimatedTokens>o&&n.estimatedTokens<=t)}generateReport(){let e=this.getAllStates();if(e.length===0)return"No conversations tracked yet.";let t=this.config.pruneThreshold||1e5,o=["Context Window State Report","==========================",`Report Generated: ${new Date().toISOString()}`,`Context Window Limit: ${t} tokens`,`Total Conversations: ${e.length}`,""],n=e.reduce((d,g)=>d+g.estimatedTokens,0),s=e.reduce((d,g)=>d+g.pruneCount,0),i=e.reduce((d,g)=>d+g.summarizationCount,0),a=Math.round(n/e.length);o.push("Summary:"),o.push(`- Total tokens across all conversations: ${n}`),o.push(`- Average tokens per conversation: ${a}`),o.push(`- Total prune operations: ${s}`),o.push(`- Total summarizations: ${i}`),o.push("");let c=this.getAtRiskConversations();c.length>0&&(o.push(`At-Risk Conversations (80%+ threshold): ${c.length}`),c.forEach(d=>{let g=Math.round(d.estimatedTokens/t*100);o.push(`- ${d.conversationId}: ${d.estimatedTokens}/${t} tokens (${g}%)`)}),o.push(""));let p=this.getExceedingThreshold();return p.length>0&&(o.push(`Exceeded Conversations: ${p.length}`),p.forEach(d=>{let g=d.estimatedTokens-t;o.push(`- ${d.conversationId}: ${d.estimatedTokens}/${t} tokens (+${g} over)`)}),o.push("")),o.push("Most Active Conversations (by operations):"),[...e].sort((d,g)=>{let w=d.pruneCount+d.summarizationCount;return g.pruneCount+g.summarizationCount-w}).slice(0,5).forEach(d=>{let g=d.pruneCount+d.summarizationCount;o.push(`- ${d.conversationId}: ${d.pruneCount} prunes, ${d.summarizationCount} summarizations (${g} operations)`)}),o.join(`
401
+ `)}export(){let e={};for(let[t,o]of this.states.entries())e[t]={...o,lastUpdated:o.lastUpdated,lastPrunedAt:o.lastPrunedAt};return e}import(e){for(let[t,o]of Object.entries(e))this.states.set(t,{...o,lastUpdated:typeof o.lastUpdated=="number"?o.lastUpdated:new Date(o.lastUpdated).getTime(),lastPrunedAt:o.lastPrunedAt&&typeof o.lastPrunedAt!="number"?new Date(o.lastPrunedAt).getTime():o.lastPrunedAt})}pruneInactiveConversations(e=60){let t=Date.now()-e*60*1e3,o=[];for(let[n,s]of this.states.entries())s.lastUpdated<t&&o.push(n);return o.forEach(n=>this.states.delete(n)),o}getMemoryUsage(){let e=this.states.size,t=e*500;return{conversationCount:e,approximateByteSize:t}}validateIntegrity(){let e=[];for(let[t,o]of this.states.entries())(!t||typeof t!="string")&&e.push(`Invalid conversation ID: ${t}`),o.estimatedTokens<0&&e.push(`Negative token count for ${t}: ${o.estimatedTokens}`),o.pruneCount<0&&e.push(`Negative prune count for ${t}: ${o.pruneCount}`),o.summarizationCount<0&&e.push(`Negative summarization count for ${t}: ${o.summarizationCount}`),o.warningsSent<0&&e.push(`Negative warning count for ${t}: ${o.warningsSent}`),(typeof o.lastUpdated!="number"||o.lastUpdated<=0)&&e.push(`Invalid lastUpdated timestamp for ${t}`),o.lastPrunedAt!==void 0&&(typeof o.lastPrunedAt!="number"||o.lastPrunedAt<=0)&&e.push(`Invalid lastPrunedAt timestamp for ${t}`);return{isValid:e.length===0,issues:e}}};function Ta(r){return new Kr(r)}l();Wt();var Ut=class{discoveryCache=new ht;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(Ye()),s.add(Xe);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=ht.fromMessages(e);this.discoveryCache.merge(c);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let d=t.get(m);d&&!s.has(m)&&d.cacheable!==!1&&(n.push(this.toSchema(d)),s.add(m))}}return n}resolveLegacy(e,t){let o;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)o=e.getEnabled();else{let n=e.getByNames(t.enabledTools),s=e.getByCategories(t.enabledToolCategories),i=new Set;o=[];for(let a of[...n,...s])i.has(a.name)||(i.add(a.name),o.push(a))}return o.map(n=>this.toSchema(n))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};l();var Xw={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},ne={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:Xw};Wt();l();function Sa(r){if(r.disabled)return"";let e=r.includeWorkingDirectory!==!1,t=r.includeToolCategories!==!1,o=e?`
402
402
  Working directory: ${r.workingDirectory}`:"",n=t&&r.toolCategories.length>0?`
403
403
  Available tool categories: ${r.toolCategories.join(", ")}`:"";return`You are an AI assistant with access to tools that let you interact with the user's system.${o}${n}
404
404
 
405
405
  When the user asks you to do something, be proactive:
406
406
  - Use your tools to find information rather than asking the user for details you can discover yourself
407
407
  - Read files, list directories, and explore the codebase when asked to analyze or understand a project
408
- - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}c();var wt=class{analyticalPatterns=[/\b(analyze|find|search|check|list|show)\b/i,/\b(biggest|largest|smallest|most|least|all|every|count)\b/i,/\b(explain|understand|review|audit|inspect|examine)\b/i,/\b(compare|difference|similar|match|pattern)\b/i,/\b(what|where|how many|which|who|when|why|how)\b/i,/\?$/];actionPatterns=[/\b(create|write|update|modify|edit|patch|delete|remove|rename|move|copy)\b/i,/\b(run|execute|start|stop|restart|deploy|install|build)\b/i,/\b(fix|refactor|implement|add|change|replace|insert)\b/i,/\b(make|do|set|configure|setup|initialize)\b/i];classify(e){if(!e||e.trim().length===0)return{type:"conversational",confidence:0};let t=e.toLowerCase(),o=this.analyticalPatterns.filter(a=>a.test(t)).length,n=this.actionPatterns.filter(a=>a.test(t)).length,s=o/this.analyticalPatterns.length,i=n/this.actionPatterns.length;if(o>n&&o>0){let a=Math.min(s,1);return n>0&&(a=Math.min(a,.5)),{type:"analytical",confidence:a,reasoning:`Matched ${o} analytical patterns${n>0?`, ${n} action patterns (capped confidence)`:""}`}}else return n>o&&n>0?{type:"action",confidence:Math.min(i,1),reasoning:`Matched ${n} action patterns`}:o===n&&o>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${o} analytical, ${n} action patterns)`}:{type:"conversational",confidence:.3,reasoning:"No strong analytical or action patterns detected"}}getToolRoundsAdjustment(e,t){return e.type==="analytical"&&e.confidence>.6?Math.min(t+3,10):(e.type==="action"&&e.confidence>.6,t)}};c();var _n=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let n=e[o],s=[],i=JSON.stringify(n.arguments).toLowerCase();for(let a=0;a<o;a++){let l=e[a];this.hasDependency(n,l,i)&&s.push(l.id)}t.push({toolCallId:n.id,dependsOn:s})}return t}hasDependency(e,t,o){if(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&o.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&o.includes(t.arguments.url.toLowerCase()))return!0;let s=["github.pr.files.list","github.pr.diff.get","github.contents.getText"];if(["github.pr.reviews.submit","github.pr.reviewComments.reply"].includes(e.name)&&s.includes(t.name)||e.name==="github.contents.getText"&&t.name==="github.pr.files.list"||e.name==="github.pr.reviewThreads.resolve"&&t.name==="github.pr.reviewThreads.list")return!0;let a=["slack.conversations.history","slack.conversations.replies"];return!!(["slack.chat.postMessage","slack.chat.postEphemeral"].includes(e.name)&&a.includes(t.name)||e.name==="slack.reactions.add"&&a.includes(t.name))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let n=this.analyzeDependencies(e),s=new Map,i=new Set;for(;i.size<e.length;){let a=[];for(let p of e){if(i.has(p.id))continue;(n.find(g=>g.toolCallId===p.id)?.dependsOn.every(g=>i.has(g))??!0)&&a.push(p)}if(a.length===0){let p=e.filter(m=>!i.has(m.id));throw new Error(`Circular dependency detected in tool calls: ${p.map(m=>m.name).join(", ")}`)}let l=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:m}of l)s.set(p,m),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let n=async i=>(await Promise.allSettled(i.map(async l=>({id:l.id,result:await t(l)})))).map((l,p)=>l.status==="fulfilled"?l.value:{id:i[p].id,result:JSON.stringify({error:l.reason?.message??"Tool execution failed"})});if(e.length<=o)return n(e);let s=[];for(let i=0;i<e.length;i+=o)s.push(...await n(e.slice(i,i+o)));return s}shouldUseParallelExecution(e){return e.length>=2}};c();function et(r){for(let e=r.length-1;e>=0;e--){let t=r[e];if(t?.role!=="user")continue;let o=t?.content;return typeof o=="string"?o:Array.isArray(o)?o.map(n=>n?.type==="text"?n.text:"").filter(Boolean).join(`
409
- `):""}return""}S();c();c();import{readFile as mT,readdir as dT}from"fs/promises";import{resolve as uT,join as rs,extname as fT}from"path";c();function Ia(r){return r.trim()}var gT=".toolpack/rules",xt=class{fileCache=new Map;modeCache=new Map;async loadForMode(e,t){let o=t??gT,n=`${e}:${o}`;if(this.modeCache.has(n))return this.modeCache.get(n);let s=new Set;if(await this.collectFromFolder(rs(o,"__global__"),s),e&&await this.collectFromFolder(rs(o,e),s),s.size===0)return this.modeCache.set(n,""),"";let i=[];for(let l of s){let p=await this.readFileCached(l);if(!p)continue;let m=Ia(p);m&&i.push(m)}if(i.length===0)return this.modeCache.set(n,""),"";let a=`<rules>
410
- ${i.join(`
408
+ - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}l();var wt=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 Cn=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let n=e[o],s=[],i=JSON.stringify(n.arguments).toLowerCase();for(let a=0;a<o;a++){let c=e[a];this.hasDependency(n,c,i)&&s.push(c.id)}t.push({toolCallId:n.id,dependsOn:s})}return t}hasDependency(e,t,o){if(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&o.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&o.includes(t.arguments.url.toLowerCase()))return!0;let s=["github.pr.files.list","github.pr.diff.get","github.contents.getText"];if(["github.pr.reviews.submit","github.pr.reviewComments.reply"].includes(e.name)&&s.includes(t.name)||e.name==="github.contents.getText"&&t.name==="github.pr.files.list"||e.name==="github.pr.reviewThreads.resolve"&&t.name==="github.pr.reviewThreads.list")return!0;let a=["slack.conversations.history","slack.conversations.replies"];return!!(["slack.chat.postMessage","slack.chat.postEphemeral"].includes(e.name)&&a.includes(t.name)||e.name==="slack.reactions.add"&&a.includes(t.name))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let n=this.analyzeDependencies(e),s=new Map,i=new Set;for(;i.size<e.length;){let a=[];for(let p of e){if(i.has(p.id))continue;(n.find(g=>g.toolCallId===p.id)?.dependsOn.every(g=>i.has(g))??!0)&&a.push(p)}if(a.length===0){let p=e.filter(m=>!i.has(m.id));throw new Error(`Circular dependency detected in tool calls: ${p.map(m=>m.name).join(", ")}`)}let c=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:m}of c)s.set(p,m),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let n=async i=>(await Promise.allSettled(i.map(async c=>({id:c.id,result:await t(c)})))).map((c,p)=>c.status==="fulfilled"?c.value:{id:i[p].id,result:JSON.stringify({error:c.reason?.message??"Tool execution failed"})});if(e.length<=o)return n(e);let s=[];for(let i=0;i<e.length;i+=o)s.push(...await n(e.slice(i,i+o)));return s}shouldUseParallelExecution(e){return e.length>=2}};l();function Ze(r){for(let e=r.length-1;e>=0;e--){let t=r[e];if(t?.role!=="user")continue;let o=t?.content;return typeof o=="string"?o:Array.isArray(o)?o.map(n=>n?.type==="text"?n.text:"").filter(Boolean).join(`
409
+ `):""}return""}S();l();l();import{readFile as nT,readdir as rT}from"fs/promises";import{resolve as sT,join as Xr,extname as iT}from"path";l();function Ea(r){return r.trim()}var aT=".toolpack/rules",lT=3e4,xt=class{constructor(e=lT){this.cacheTtlMs=e}cacheTtlMs;modeCache=new Map;async loadForMode(e,t){let o=t??aT,n=`${e}:${o}`,s=this.modeCache.get(n);if(s&&Date.now()-s.cachedAt<this.cacheTtlMs)return s.value;let i=new Set;if(await this.collectFromFolder(Xr(o,"__global__"),i),e&&await this.collectFromFolder(Xr(o,e),i),i.size===0)return this.modeCache.set(n,{value:"",cachedAt:Date.now()}),"";let a=new Map,c=[];for(let m of i){let d=await this.readFile(m,a);if(!d)continue;let g=Ea(d);g&&c.push(g)}let p=c.length===0?"":`<rules>
410
+ ${c.join(`
411
411
 
412
412
  `)}
413
- </rules>`;return this.modeCache.set(n,a),a}async collectFromFolder(e,t){let o=uT(e);try{await this.collectRecursive(o,t)}catch{}}async collectRecursive(e,t){let o=await dT(e,{withFileTypes:!0});for(let n of o){let s=rs(e,n.name);n.isDirectory()?await this.collectRecursive(s,t):n.isFile()&&fT(n.name)===".md"&&t.add(s)}}async readFileCached(e){if(this.fileCache.has(e))return this.fileCache.get(e);try{let t=await mT(e,"utf-8");return this.fileCache.set(e,t),t}catch{return""}}};var ja=0;function La(){return ja+=1,`${Date.now()}-${ja}`}function Rn(r,e){tt("debug")&&(y(`[AIClient][${r}] Messages (${e.length}):`),e.forEach((t,o)=>{let n=A(t.content,300);y(`[AIClient][${r}] #${o} role=${t.role} content=${n}`)}))}function Fa(r){let e=et(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 qa(r){let e=et(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 $n=class extends hT{providers;defaultProvider;toolRegistry;toolsConfig;toolRouter;bm25Engine;queryClassifier;toolOrchestrator;activeMode=null;overrideSystemPrompt;disableBaseContext;toolResultMaxChars;hitlConfig;onToolConfirm;currentRound=0;conversationId;contextWindowConfig;contextWindowStateManager;providerModelCache=new Map;ruleLoader;constructor(e){super(),this.providers=new Map(Object.entries(e.providers)),this.defaultProvider=e.defaultProvider,this.toolRegistry=e.toolRegistry,this.toolsConfig=e.toolsConfig||ce,this.toolRouter=new Bt,this.bm25Engine=new Ut,this.queryClassifier=new wt,this.toolOrchestrator=new _n,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??ce.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.ruleLoader=new xt,this.contextWindowConfig&&this.contextWindowConfig.enabled!==!1&&(this.contextWindowStateManager=Pa(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:Ta(e.messages,o,t.getDisplayName().toLowerCase())}async pruneConversation(e,t,o){let n=this.contextWindowConfig?.retainSystemMessages??!0,s=e;for(let i=0;i<3;i+=1){let a=await this.countRequestTokens(s,t,s.model);if(a<=o)return s;let l=a-o,p=va(s.messages,l,n),m=new Set(p.pruneInfo.removedMessages),d=s.messages.filter(w=>!m.has(w)),g={...s,messages:d};if(this.contextWindowStateManager&&this.contextWindowStateManager.recordPruneOperation(this.getConversationId(),p.tokensReclaimed),await this.countRequestTokens(g,t,g.model)<=o||d.length===s.messages.length)return g;s=g}return e}async pruneToMaxMessageHistory(e){let t=this.contextWindowConfig?.maxMessageHistoryLength;if(!t||e.messages.length<=t)return e;let o=this.contextWindowConfig?.retainSystemMessages??!0,n=[];e.messages.forEach((l,p)=>{o&&l.role==="system"||l.role!=="tool"&&n.push(p)});let s=Math.max(0,e.messages.length-t);if(s===0)return e;let i=new Set(n.slice(0,s)),a=e.messages.filter((l,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,n=o.filter(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 l=this.contextWindowConfig?.summarizerModel||e.model,p=ka(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 Wt("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let d=await this.countRequestTokens({...e,messages:a},t,l),g=Sa(m.content,a,d),b=Ca(g);if(!b.valid)throw new Wt(`Summarization result is invalid: ${b.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",m.content);let w=Zr(g.summary,a.length),T=[...n,w,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),g.tokensSaved),{...e,messages:T}}async enforceContextWindow(e,t){if(!this.contextWindowConfig||this.contextWindowConfig.enabled===!1)return e;let o=await this.pruneToMaxMessageHistory(e),n=await this.getModelInfo(t,o.model),s=n?.contextWindow??1e5,i=o.max_tokens??n?.maxOutputTokens??1024,a=this.contextWindowConfig.outputTokenBuffer??1.15,l=xa(i,a),p=Math.max(0,s-l),m=Math.floor(s*((this.contextWindowConfig.pruneThreshold??85)/100)),d=Math.min(p,m),g=await this.countRequestTokens(o,t,o.model);if(this.contextWindowStateManager&&(this.contextWindowStateManager.updateTokenCount(this.getConversationId(),g),g>d&&this.contextWindowStateManager.recordWarning(this.getConversationId())),g<=d)return o;let b=this.contextWindowConfig.strategy??"prune";if(b==="fail"&&g>p)throw new qt("Context window exceeded by request messages",this.getConversationId(),g,p,b);if(b==="summarize")try{let T=await this.summarizeConversation(o,t);if(await this.countRequestTokens(T,t,T.model)<=p)return T;o=await this.pruneConversation(T,t,p)}catch{o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let w=await this.countRequestTokens(o,t,o.model);if(w>p&&b==="fail")throw new qt("Context window exceeded after attempted cleanup",this.getConversationId(),w,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 j("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new j(`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 j(`Provider '${e}' not found`,"PROVIDER_NOT_FOUND",404);this.defaultProvider=e}getToolRegistry(){return this.toolRegistry}getProviders(){return new Map(this.providers)}setToolRegistry(e){this.toolRegistry=e}setToolsConfig(e){this.toolsConfig=e}setSystemPrompt(e){this.overrideSystemPrompt=e}setMode(e){this.activeMode=e,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=La(),s=this.resolveRequestMode(e),i=this.injectBaseAgentContext(e,s);i=this.injectOverrideSystemPrompt(i),i=this.injectModeSystemPrompt(i,s),i=await this.injectModeRules(i,s);let a=t||this.defaultProvider,l=await this.enrichRequestWithTools(i,s),p=l.request,m=l.requestToolMap;p=await this.enforceContextWindow(p,o);let d=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",g=(p.tools?.length||0)>0,b=p.tool_choice!=null,w=Fa(p.messages),T=qa(p.messages);!b&&g&&(d==="required"||d==="required_for_actions"&&w)&&(p.tool_choice="required");let C=o?.constructor?.name||"UnknownProvider",x=s?.response_format,D={...this.stripRequestTools(p),__toolpack_request_id:n,...x?{response_format:x}:{}};P(`[AIClient][${n}] generate() start provider=${a} class=${C} model=${p.model} messages=${p.messages.length} tools=${p.tools?.length||0} tool_choice=${p.tool_choice??"unset"} policy=${d} needsTools=${w} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Rn(n,p.messages);let M=$=>ba(()=>o.generate($),{onRetry:(E,R)=>P(`[AIClient][${n}] Rate limited \u2014 retrying in ${R/1e3}s (attempt ${E}/3)`)}),k=await M(D);if(y(`[AIClient][${n}] generate() initial response finish_reason=${k.finish_reason??"unknown"} tool_calls=${k.tool_calls?.length||0} content_preview=${A(k.content||"",200)}`),this.toolsConfig.autoExecute&&(this.toolRegistry||m.size>0)){let $=et(p.messages),E=this.queryClassifier.classify($),R=this.toolsConfig.maxToolRounds,N=p.maxToolRounds!==void 0?p.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(E,R);p.maxToolRounds!==void 0?y(`[AIClient][${n}] maxToolRounds overridden per-request: ${N} (classifier bypassed)`):N!==R?P(`[AIClient][${n}] Query classified as ${E.type} (confidence: ${E.confidence.toFixed(2)}), adjusted maxToolRounds: ${R} \u2192 ${N}`):y(`[AIClient][${n}] Query classified as ${E.type} (confidence: ${E.confidence.toFixed(2)}), keeping maxToolRounds: ${N}`);let ue=0,X=[...p.messages];for(k.tool_calls&&k.tool_calls.length>0&&P(`[AIClient] Received ${k.tool_calls.length} tool call(s): ${k.tool_calls.map(dt=>dt.name).join(", ")}`);k.tool_calls&&k.tool_calls.length>0&&ue<N;){ue++,this.currentRound=ue,P(`[AIClient][${n}] generate() tool round ${ue}/${N} tool_calls=${k.tool_calls.length}`),X.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 dt=this.toolOrchestrator.shouldUseParallelExecution(k.tool_calls),ut=3,le=k.tool_calls,De=k.tool_calls.filter(K=>K.name==="web.fetch");if(De.length>ut){P(`[AIClient][${n}] Limiting web.fetch calls from ${De.length} \u2192 ${ut} to prevent context overflow`);let K=De.slice(0,ut);le=[...k.tool_calls.filter(ge=>ge.name!=="web.fetch"),...K];let z=De.slice(ut);for(let ge of z)X.push({role:"tool",tool_call_id:ge.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let oe=5e4,fe=0;if(dt){P(`[AIClient][${n}] Using parallel execution for ${le.length} tools`);let K;try{K=await this.toolOrchestrator.executeWithDependencies(le,U=>this.executeTool(U,m,s),5)}catch(U){pe(`[AIClient][${n}] Parallel tool execution failed: ${U.message}`),K=new Map(le.map(z=>[z.id,JSON.stringify({error:U.message??"Tool execution failed"})]))}for(let U of le){let z=K.get(U.id)??JSON.stringify({error:"Tool execution result missing"}),ge=typeof z=="string"?z:JSON.stringify(z),Me=oe-fe,Y=ge.startsWith("data:image/"),_;Y?_=ge:fe+ge.length>oe?(L(`[AIClient][${n}] Tool output budget exceeded (${oe} chars)`),_=this.budgetTruncate(ge,Me)):typeof z=="string"&&z.length>this.toolResultMaxChars?_=`${z.slice(0,this.toolResultMaxChars)}
414
- [TRUNCATED tool result: ${z.length} chars]`:_=ge;let J=typeof _=="string"?_:JSON.stringify(_);Y||(fe+=J.length),X.push({role:"tool",tool_call_id:U.id,content:_})}y(`[AIClient][${n}] Round tool output size: ${fe} chars (budget: ${oe})`)}else{P(`[AIClient][${n}] Using sequential execution for ${le.length} tools`);for(let K of le){let U;try{U=await this.executeTool(K,m,s)}catch(J){U=JSON.stringify({error:J.message??"Tool execution failed"})}let z=typeof U=="string"?U:JSON.stringify(U),ge=oe-fe,Me=z.startsWith("data:image/"),Y;Me?Y=z:fe+z.length>oe?(L(`[AIClient][${n}] Tool output budget exceeded (${oe} chars)`),Y=this.budgetTruncate(z,ge)):typeof U=="string"&&U.length>this.toolResultMaxChars?Y=`${U.slice(0,this.toolResultMaxChars)}
415
- [TRUNCATED tool result: ${U.length} chars]`:Y=z;let _=typeof Y=="string"?Y:JSON.stringify(Y);Me||(fe+=_.length),X.push({role:"tool",tool_call_id:K.id,content:Y})}y(`[AIClient][${n}] Round tool output size: ${fe} chars (budget: ${oe})`)}let ft={...p,messages:X,__toolpack_request_id:n,...x?{response_format:x}:{}},xe=this.stripRequestTools((await this.enrichRequestWithTools(ft,s)).request);xe=await this.enforceContextWindow(xe,o),xe.tool_choice==="required"&&(xe.tool_choice=T?"none":"auto",P(`[AIClient][${n}] generate() followup tool_choice override required->${xe.tool_choice}`)),tt("debug")&&(y(`[AIClient][${n}] generate() followup request messages=${X.length}`),Rn(n,X)),k=await M(xe),y(`[AIClient][${n}] generate() followup response finish_reason=${k.finish_reason??"unknown"} tool_calls=${k.tool_calls?.length||0} content_preview=${A(k.content||"",200)}`)}}return k.data===void 0&&k.content&&e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(k.data=e.response_format.parse(JSON.parse(k.content))),k}catch(n){throw this.wrapError(n)}}async*stream(e,t){let o=this.getProvider(t);try{let n=La(),s=t||this.defaultProvider,i=this.resolveRequestMode(e),a=this.injectBaseAgentContext(e,i);a=this.injectOverrideSystemPrompt(a),a=this.injectModeSystemPrompt(a,i),a=await this.injectModeRules(a,i);let l=await this.enrichRequestWithTools(a,i),p=l.request,m=l.requestToolMap;p=await this.enforceContextWindow(p,o);let d=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",g=(p.tools?.length||0)>0,b=p.tool_choice!=null,w=Fa(p.messages),T=qa(p.messages);!b&&g&&(d==="required"||d==="required_for_actions"&&w)&&(p.tool_choice="required");let C=o?.constructor?.name||"UnknownProvider",x=i?.response_format,D={...this.stripRequestTools(p),__toolpack_request_id:n,...x?{response_format:x}:{}};if(P(`[AIClient][${n}] stream() start provider=${s} class=${C} model=${p.model} messages=${p.messages.length} tools=${p.tools?.length||0} tool_choice=${p.tool_choice??"unset"} policy=${d} needsTools=${w} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Rn(n,p.messages),!this.toolsConfig.autoExecute||!this.toolRegistry&&m.size===0){yield*o.stream(D);return}let M=[...p.messages],k=0,$=et(p.messages),E=this.queryClassifier.classify($),R=this.toolsConfig.maxToolRounds,N=p.maxToolRounds!==void 0?p.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(E,R);for(p.maxToolRounds!==void 0?y(`[AIClient][${n}] stream() maxToolRounds overridden per-request: ${N} (classifier bypassed)`):N!==R&&P(`[AIClient][${n}] stream() Query classified as ${E.type} (confidence: ${E.confidence.toFixed(2)}), adjusted maxToolRounds: ${R} \u2192 ${N}`);k<=N;){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal`);return}let ue="",X=[];k++,this.currentRound=k,P(`[AIClient][${n}] stream() round_start ${k}/${N}`);let dt=null,ut={...p,messages:M,...x?{response_format:x}:{}},le=this.stripRequestTools((await this.enrichRequestWithTools(ut,i)).request);le=await this.enforceContextWindow(le,o),k>1&&le.tool_choice==="required"&&(le.tool_choice=T?"none":"auto",P(`[AIClient][${n}] stream() round_${k} tool_choice override required->${le.tool_choice}`));for await(let _ of o.stream(le)){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal during chunk processing`);return}_.tool_calls&&_.tool_calls.length>0&&(X.push(..._.tool_calls),y(`[AIClient][${n}] stream() tool_calls_chunk count=${_.tool_calls.length} names=${_.tool_calls.map(J=>J.name).join(", ")}`),yield _),_.delta&&(ue+=_.delta,yield _),_.finish_reason&&(dt=_.finish_reason),_.finish_reason==="stop"&&(yield _)}if(y(`[AIClient][${n}] stream() round_end finish_reason=${dt??"unknown"} accumulated_len=${ue.length} tool_calls_total=${X.length} content_preview=${A(ue,200)}`),X.length===0)break;P(`[AIClient][${n}] stream() received ${X.length} tool call(s): ${X.map(_=>_.name).join(", ")}`),P(`[AIClient][${n}] stream() tool round ${k}/${N}`),M.push({role:"assistant",content:ue||"",tool_calls:X.map(_=>({id:_.id,type:"function",function:{name:_.name,arguments:JSON.stringify(_.arguments)}}))});let De=3,oe=X,fe=X.filter(_=>_.name==="web.fetch");if(fe.length>De){P(`[AIClient][${n}] Limiting web.fetch calls from ${fe.length} \u2192 ${De} to prevent context overflow`);let _=fe.slice(0,De);oe=[...X.filter(Ft=>Ft.name!=="web.fetch"),..._];let ve=fe.slice(De);for(let Ft of ve)M.push({role:"tool",tool_call_id:Ft.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ft=5e4,xe=0,K=[],U=!1,z=setInterval(()=>{U||K.push({delta:""})},500),ge=Date.now(),Me,Y;try{if(oe.length>=2)P(`[AIClient][${n}] stream() using parallel execution for ${oe.length} tools`),Y=new Map,Me=await this.toolOrchestrator.executeWithDependencies(oe,async _=>{let J=Date.now(),ve=await this.executeTool(_,m,i);return Y.set(_.id,Date.now()-J),ve},5);else{P(`[AIClient][${n}] stream() executing single tool sequentially`),Y=new Map,Me=new Map;for(let _ of oe){let J=Date.now(),ve=await this.executeTool(_,m,i);Y.set(_.id,Date.now()-J),Me.set(_.id,ve)}}}finally{U=!0,clearInterval(z)}for(;K.length>0;)yield K.shift();await new Promise(_=>setTimeout(_,0)),y(`[AIClient][${n}] stream() tool batch completed in ${Date.now()-ge}ms`);for(let _ of oe){let J=Me.get(_.id),ve=typeof J=="string"?J:JSON.stringify(J),Ft=ft-xe,Gw=Y.get(_.id)??0,da=ve.startsWith("data:image/"),Ie;da?Ie=ve:xe+ve.length>ft?(L(`[AIClient][${n}] Tool output budget exceeded (${ft} chars)`),Ie=this.budgetTruncate(ve,Ft)):typeof J=="string"&&J.length>this.toolResultMaxChars?Ie=`${J.slice(0,this.toolResultMaxChars)}
416
- [TRUNCATED tool result: ${J.length} chars]`:Ie=ve;let ua=typeof Ie=="string"?Ie:JSON.stringify(Ie);da||(xe+=ua.length),M.push({role:"tool",tool_call_id:_.id,content:Ie}),yield{delta:"",tool_calls:[{..._,result:ua,duration:Gw}]}}y(`[AIClient][${n}] Round tool output size: ${xe} chars (budget: ${ft})`),tt("debug")&&(y(`[AIClient][${n}] stream() after_tools messages=${M.length}`),Rn(n,M))}}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,t){if(t?.blockAllTools)return P(`[AIClient] Mode "${t.displayName}" blocks all tools`),{request:e,requestToolMap:new Map};let o=this.buildRequestToolMap(e.requestTools),n=Array.from(o.values()).map(d=>this.requestToolToSchema(d)),s=o.size>0;if(!this.toolsConfig.enabled&&!s)return y("[AIClient] Tools disabled and no request-scoped tools"),{request:e,requestToolMap:o};let i=this.toolsConfig;if(t?.toolSearch&&this.toolsConfig.toolSearch&&(i={...this.toolsConfig,toolSearch:{...this.toolsConfig.toolSearch,...t.toolSearch.enabled!==void 0?{enabled:t.toolSearch.enabled}:{},...t.toolSearch.alwaysLoadedTools?{alwaysLoadedTools:t.toolSearch.alwaysLoadedTools}:{},...t.toolSearch.alwaysLoadedCategories?{alwaysLoadedCategories:t.toolSearch.alwaysLoadedCategories}:{}}},y(`[AIClient] Merged mode toolSearch config: enabled=${i.toolSearch?.enabled}, alwaysLoadedTools=${i.toolSearch?.alwaysLoadedTools?.length||0}`)),e.tools&&e.tools.length>0){if(!i.toolSearch?.enabled||!this.toolRegistry){y(`[AIClient] Request already has ${e.tools.length} tools`);let T=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(n)),v=T===e.tools?e:{...e,tools:T};return{request:this.injectRequestToolGuidance(v,T),requestToolMap:o}}let d=await this.toolRouter.resolve(e.messages,this.toolRegistry,i);if(y(`[AIClient] Resolved ${d.length} tools to send: ${d.map(T=>T.name).join(", ")||"none"}`),t&&d.length>0){let T=d.length;d=this.filterSchemasByMode(d,t);let v=T-d.length;v>0&&P(`[AIClient] Mode "${t.displayName}" filtered out ${v} tools`)}let g=new Set(e.tools.map(T=>T.function.name)),b=d.filter(T=>!g.has(T.name)).map(T=>({type:"function",function:{name:T.name,description:T.description,parameters:T.parameters}}));if(b.length===0){y(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`);let T=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(n)),v=T===e.tools?e:{...e,tools:T};return{request:this.injectRequestToolGuidance(v,T),requestToolMap:o}}let w={...e,tools:this.mergeToolCallRequests([...e.tools,...b],this.schemasToToolCallRequests(n))};return i.toolSearch?.enabled&&this.toolRegistry&&(w=this.injectToolSearchPrompt(w)),{request:this.injectRequestToolGuidance(w,w.tools),requestToolMap:o}}if(!this.toolRegistry){y("[AIClient] Tool registry not configured, skipping tool resolution");let d=this.schemasToToolCallRequests(n),g=d.length>0?{...e,tools:d}:e;return{request:this.injectRequestToolGuidance(g,d),requestToolMap:o}}let a=this.toolRegistry,l=await this.toolRouter.resolve(e.messages,a,i);if(y(`[AIClient] Resolved ${l.length} tools to send: ${l.map(d=>d.name).join(", ")||"none"}`),t&&l.length>0){let d=l.length;l=this.filterSchemasByMode(l,t);let g=d-l.length;g>0&&P(`[AIClient] Mode "${t.displayName}" filtered out ${g} tools`)}let p=this.schemasToToolCallRequests(this.mergeSchemas(l,n));if(p.length===0)return{request:e,requestToolMap:o};let m={...e,tools:p};return this.toolsConfig.toolSearch?.enabled&&a&&(m=this.injectToolSearchPrompt(m)),{request:this.injectRequestToolGuidance(m,p),requestToolMap:o}}buildRequestToolMap(e){let t=new Map;for(let o of e||[])t.set(o.name,o);return t}requestToolToSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category,cacheable:e.cacheable}}mergeSchemas(e,t){let o=new Map;for(let n of e)o.set(n.name,n);for(let n of t)o.set(n.name,n);return Array.from(o.values())}schemasToToolCallRequests(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}))}mergeToolCallRequests(e,t){if(t.length===0)return e;let o=new Map;for(let n of e)o.set(n.function.name,n);for(let n of t)o.set(n.function.name,n);return Array.from(o.values())}injectRequestToolGuidance(e,t){let o=new Set((t||e.tools||[]).map(l=>l.function.name));if(o.size===0)return e;let n="<!-- TOOLPACK_REQUEST_TOOL_GUIDANCE -->",s=[];if(o.has("knowledge_search")||o.has("knowledge_add")){let l=["Knowledge Base:"];o.has("knowledge_search")&&l.push("- Use `knowledge_search` when you need factual or domain-specific information that may already be stored."),o.has("knowledge_add")&&l.push("- Use `knowledge_add` when you encounter a durable fact, user preference, or decision that future conversations should know. Do not add confidential information, routine task outputs, or context that is specific to this conversation only."),s.push(l.join(`
413
+ </rules>`;return this.modeCache.set(n,{value:p,cachedAt:Date.now()}),p}clearCache(){this.modeCache.clear()}async collectFromFolder(e,t){let o=sT(e);try{await this.collectRecursive(o,t)}catch{}}async collectRecursive(e,t){let o=await rT(e,{withFileTypes:!0});for(let n of o){let s=Xr(e,n.name);n.isDirectory()?await this.collectRecursive(s,t):n.isFile()&&iT(n.name)===".md"&&t.add(s)}}async readFile(e,t){if(t.has(e))return t.get(e);try{let o=await nT(e,"utf-8");return t.set(e,o),o}catch{return""}}};function kn(r,e){Tt("debug")&&(y(`[AIClient][${r}] Messages (${e.length}):`),e.forEach((t,o)=>{let n=D(t.content,300);y(`[AIClient][${r}] #${o} role=${t.role} content=${n}`)}))}function Da(r){let e=Ze(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 Ma(r){let e=Ze(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 Sn=class extends cT{providers;defaultProvider;toolRegistry;toolsConfig;toolRouter;bm25Engine;queryClassifier;toolOrchestrator;activeMode=null;overrideSystemPrompt;disableBaseContext;toolResultMaxChars;hitlConfig;onToolConfirm;conversationId;contextWindowConfig;contextWindowStateManager;providerModelCache=new Map;ruleLoader;requestSeq=0;constructor(e){super(),this.providers=new Map(Object.entries(e.providers)),this.defaultProvider=e.defaultProvider,this.toolRegistry=e.toolRegistry,this.toolsConfig=e.toolsConfig||ne,this.toolRouter=new Ut,this.bm25Engine=new qt,this.queryClassifier=new wt,this.toolOrchestrator=new Cn,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??ne.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.ruleLoader=new xt,this.contextWindowConfig&&this.contextWindowConfig.enabled!==!1&&(this.contextWindowStateManager=Ta(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:fa(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=ha(s.messages,c,n),m=new Set(p.pruneInfo.removedMessages),d=s.messages.filter(b=>!m.has(b)),g={...s,messages:d};if(this.contextWindowStateManager&&this.contextWindowStateManager.recordPruneOperation(this.getConversationId(),p.tokensReclaimed),await this.countRequestTokens(g,t,g.model)<=o||d.length===s.messages.length)return g;s=g}return e}async pruneToMaxMessageHistory(e){let t=this.contextWindowConfig?.maxMessageHistoryLength;if(!t||e.messages.length<=t)return e;let o=this.contextWindowConfig?.retainSystemMessages??!0,n=[];e.messages.forEach((c,p)=>{o&&c.role==="system"||c.role!=="tool"&&n.push(p)});let s=Math.max(0,e.messages.length-t);if(s===0)return e;let i=new Set(n.slice(0,s)),a=e.messages.filter((c,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,n=o.filter(k=>k.role==="system"),s=o.filter(k=>k.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=ba(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 Ft("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let d=await this.countRequestTokens({...e,messages:a},t,c),g=wa(m.content,a,d),w=ya(g);if(!w.valid)throw new Ft(`Summarization result is invalid: ${w.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",m.content);let b=Hr(g.summary,a.length),T=[...n,b,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),g.tokensSaved),{...e,messages:T}}async enforceContextWindow(e,t){if(!this.contextWindowConfig||this.contextWindowConfig.enabled===!1)return e;let o=await this.pruneToMaxMessageHistory(e),n=await this.getModelInfo(t,o.model),s=n?.contextWindow??1e5,i=o.max_tokens??n?.maxOutputTokens??1024,a=this.contextWindowConfig.outputTokenBuffer??1.15,c=ga(i,a),p=Math.max(0,s-c),m=Math.floor(s*((this.contextWindowConfig.pruneThreshold??85)/100)),d=Math.min(p,m),g=await this.countRequestTokens(o,t,o.model);if(this.contextWindowStateManager&&(this.contextWindowStateManager.updateTokenCount(this.getConversationId(),g),g>d&&this.contextWindowStateManager.recordWarning(this.getConversationId())),g<=d)return o;let w=this.contextWindowConfig.strategy??"prune";if(w==="fail"&&g>p)throw new jt("Context window exceeded by request messages",this.getConversationId(),g,p,w);if(w==="summarize")try{let T=await this.summarizeConversation(o,t);if(await this.countRequestTokens(T,t,T.model)<=p)return T;o=await this.pruneConversation(T,t,p)}catch{o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let b=await this.countRequestTokens(o,t,o.model);if(b>p&&w==="fail")throw new jt("Context window exceeded after attempted cleanup",this.getConversationId(),b,p,w);return o}isBypassed(e){let t=this.hitlConfig;if(!t||t.enabled===!1)return!0;let o=t.confirmationMode??"all";if(o==="off"||o==="high-only"&&e.confirmation?.level==="medium")return!0;let n=t.bypass??{};return!!(n.tools?.includes(e.name)||n.categories?.includes(e.category)||e.confirmation&&n.levels?.includes(e.confirmation.level))}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new 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=this.newRequestId(),s=this.resolveRequestMode(e),i=s?.toolsConfig?{...this.toolsConfig,...s.toolsConfig}:this.toolsConfig,a=this.injectBaseAgentContext(e,s);a=this.injectOverrideSystemPrompt(a),a=this.injectModeSystemPrompt(a,s),a=await this.injectModeRules(a,s);let c=t||this.defaultProvider,p=await this.enrichRequestWithTools(a,s),m=p.request,d=p.requestToolMap;m=await this.enforceContextWindow(m,o);let g=i.toolChoicePolicy||process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||"auto",w=(m.tools?.length||0)>0,b=m.tool_choice!=null,T=Da(m.messages),k=Ma(m.messages);!b&&w&&(g==="required"||g==="required_for_actions"&&T)&&(m.tool_choice="required");let x=o?.constructor?.name||"UnknownProvider",C=s?.response_format,_={...this.stripRequestTools(m),__toolpack_request_id:n,...C?{response_format:C}:{}};P(`[AIClient][${n}] generate() start provider=${c} class=${x} model=${m.model} messages=${m.messages.length} tools=${m.tools?.length||0} tool_choice=${m.tool_choice??"unset"} policy=${g} needsTools=${T} autoExecute=${i.enabled&&i.autoExecute}`),kn(n,m.messages);let E=te=>da(()=>o.generate(te),{onRetry:(F,G)=>P(`[AIClient][${n}] Rate limited \u2014 retrying in ${G/1e3}s (attempt ${F}/3)`)}),$=await E(_);if(y(`[AIClient][${n}] generate() initial response finish_reason=${$.finish_reason??"unknown"} tool_calls=${$.tool_calls?.length||0} content_preview=${D($.content||"",200)}`),i.autoExecute&&(this.toolRegistry||d.size>0||(s?.customTools?.length??0)>0)){let te=Ze(m.messages),F=this.queryClassifier.classify(te),G=i.maxToolRounds,q=m.maxToolRounds!==void 0?m.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(F,G);m.maxToolRounds!==void 0?y(`[AIClient][${n}] maxToolRounds overridden per-request: ${q} (classifier bypassed)`):q!==G?P(`[AIClient][${n}] Query classified as ${F.type} (confidence: ${F.confidence.toFixed(2)}), adjusted maxToolRounds: ${G} \u2192 ${q}`):y(`[AIClient][${n}] Query classified as ${F.type} (confidence: ${F.confidence.toFixed(2)}), keeping maxToolRounds: ${q}`);let _e=0,X=[...m.messages];for($.tool_calls&&$.tool_calls.length>0&&P(`[AIClient] Received ${$.tool_calls.length} tool call(s): ${$.tool_calls.map(dt=>dt.name).join(", ")}`);$.tool_calls&&$.tool_calls.length>0&&_e<q;){if(e.signal?.aborted){P(`[AIClient][${n}] generate() aborted by signal`);break}_e++,P(`[AIClient][${n}] generate() tool round ${_e}/${q} tool_calls=${$.tool_calls.length}`),X.push({role:"assistant",content:$.content||"",tool_calls:$.tool_calls.map(K=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments)}}))});let dt=this.toolOrchestrator.shouldUseParallelExecution($.tool_calls),ut=3,pe=$.tool_calls,Me=$.tool_calls.filter(K=>K.name==="web.fetch");if(Me.length>ut){P(`[AIClient][${n}] Limiting web.fetch calls from ${Me.length} \u2192 ${ut} to prevent context overflow`);let K=Me.slice(0,ut);pe=[...$.tool_calls.filter(fe=>fe.name!=="web.fetch"),...K];let z=Me.slice(ut);for(let fe of z)X.push({role:"tool",tool_call_id:fe.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let se=5e4,ue=0;if(dt){P(`[AIClient][${n}] Using parallel execution for ${pe.length} tools`);let K;try{K=await this.toolOrchestrator.executeWithDependencies(pe,W=>this.executeTool(W,d,s,_e),5)}catch(W){me(`[AIClient][${n}] Parallel tool execution failed: ${W.message}`),K=new Map(pe.map(z=>[z.id,JSON.stringify({error:W.message??"Tool execution failed"})]))}for(let W of pe){let z=K.get(W.id)??JSON.stringify({error:"Tool execution result missing"}),fe=typeof z=="string"?z:JSON.stringify(z),Ae=se-ue,Y=fe.startsWith("data:image/"),R;Y?R=fe:ue+fe.length>se?(O(`[AIClient][${n}] Tool output budget exceeded (${se} chars)`),R=this.budgetTruncate(fe,Ae)):typeof z=="string"&&z.length>this.toolResultMaxChars?R=`${z.slice(0,this.toolResultMaxChars)}
414
+ [TRUNCATED tool result: ${z.length} chars]`:R=fe;let J=typeof R=="string"?R:JSON.stringify(R);Y||(ue+=J.length),X.push({role:"tool",tool_call_id:W.id,content:R})}y(`[AIClient][${n}] Round tool output size: ${ue} chars (budget: ${se})`)}else{P(`[AIClient][${n}] Using sequential execution for ${pe.length} tools`);for(let K of pe){let W;try{W=await this.executeTool(K,d,s,_e)}catch(J){W=JSON.stringify({error:J.message??"Tool execution failed"})}let z=typeof W=="string"?W:JSON.stringify(W),fe=se-ue,Ae=z.startsWith("data:image/"),Y;Ae?Y=z:ue+z.length>se?(O(`[AIClient][${n}] Tool output budget exceeded (${se} chars)`),Y=this.budgetTruncate(z,fe)):typeof W=="string"&&W.length>this.toolResultMaxChars?Y=`${W.slice(0,this.toolResultMaxChars)}
415
+ [TRUNCATED tool result: ${W.length} chars]`:Y=z;let R=typeof Y=="string"?Y:JSON.stringify(Y);Ae||(ue+=R.length),X.push({role:"tool",tool_call_id:K.id,content:Y})}y(`[AIClient][${n}] Round tool output size: ${ue} chars (budget: ${se})`)}let ft={...m,messages:X,__toolpack_request_id:n,...C?{response_format:C}:{}},ve=this.stripRequestTools((await this.enrichRequestWithTools(ft,s)).request);ve=await this.enforceContextWindow(ve,o),ve.tool_choice==="required"&&(ve.tool_choice=k?"none":"auto",P(`[AIClient][${n}] generate() followup tool_choice override required->${ve.tool_choice}`)),Tt("debug")&&(y(`[AIClient][${n}] generate() followup request messages=${X.length}`),kn(n,X)),$=await E(ve),y(`[AIClient][${n}] generate() followup response finish_reason=${$.finish_reason??"unknown"} tool_calls=${$.tool_calls?.length||0} content_preview=${D($.content||"",200)}`)}}return $.data===void 0&&$.content&&e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&($.data=e.response_format.parse(JSON.parse($.content))),$}catch(n){throw this.wrapError(n)}}async*stream(e,t){let o=this.getProvider(t);try{let n=this.newRequestId(),s=t||this.defaultProvider,i=this.resolveRequestMode(e),a=i?.toolsConfig?{...this.toolsConfig,...i.toolsConfig}:this.toolsConfig,c=this.injectBaseAgentContext(e,i);c=this.injectOverrideSystemPrompt(c),c=this.injectModeSystemPrompt(c,i),c=await this.injectModeRules(c,i);let p=await this.enrichRequestWithTools(c,i),m=p.request,d=p.requestToolMap;m=await this.enforceContextWindow(m,o);let g=a.toolChoicePolicy||process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||"auto",w=(m.tools?.length||0)>0,b=m.tool_choice!=null,T=Da(m.messages),k=Ma(m.messages);!b&&w&&(g==="required"||g==="required_for_actions"&&T)&&(m.tool_choice="required");let x=o?.constructor?.name||"UnknownProvider",C=i?.response_format,_={...this.stripRequestTools(m),__toolpack_request_id:n,...C?{response_format:C}:{}};if(P(`[AIClient][${n}] stream() start provider=${s} class=${x} model=${m.model} messages=${m.messages.length} tools=${m.tools?.length||0} tool_choice=${m.tool_choice??"unset"} policy=${g} needsTools=${T} autoExecute=${a.enabled&&a.autoExecute}`),kn(n,m.messages),!a.autoExecute||!this.toolRegistry&&d.size===0&&(i?.customTools?.length??0)===0){yield*o.stream(_);return}let E=[...m.messages],$=0,te=Ze(m.messages),F=this.queryClassifier.classify(te),G=a.maxToolRounds,q=m.maxToolRounds!==void 0?m.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(F,G);for(m.maxToolRounds!==void 0?y(`[AIClient][${n}] stream() maxToolRounds overridden per-request: ${q} (classifier bypassed)`):q!==G&&P(`[AIClient][${n}] stream() Query classified as ${F.type} (confidence: ${F.confidence.toFixed(2)}), adjusted maxToolRounds: ${G} \u2192 ${q}`);$<=q;){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal`);return}let _e="",X=[];$++,P(`[AIClient][${n}] stream() round_start ${$}/${q}`);let dt=null,ut={...m,messages:E,...C?{response_format:C}:{}},pe=this.stripRequestTools((await this.enrichRequestWithTools(ut,i)).request);pe=await this.enforceContextWindow(pe,o),$>1&&pe.tool_choice==="required"&&(pe.tool_choice=k?"none":"auto",P(`[AIClient][${n}] stream() round_${$} tool_choice override required->${pe.tool_choice}`));for await(let R of o.stream(pe)){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal during chunk processing`);return}R.tool_calls&&R.tool_calls.length>0&&(X.push(...R.tool_calls),y(`[AIClient][${n}] stream() tool_calls_chunk count=${R.tool_calls.length} names=${R.tool_calls.map(J=>J.name).join(", ")}`),yield R),R.delta&&(_e+=R.delta,yield R),R.finish_reason&&(dt=R.finish_reason),R.finish_reason==="stop"&&(yield R)}if(y(`[AIClient][${n}] stream() round_end finish_reason=${dt??"unknown"} accumulated_len=${_e.length} tool_calls_total=${X.length} content_preview=${D(_e,200)}`),X.length===0)break;P(`[AIClient][${n}] stream() received ${X.length} tool call(s): ${X.map(R=>R.name).join(", ")}`),P(`[AIClient][${n}] stream() tool round ${$}/${q}`),E.push({role:"assistant",content:_e||"",tool_calls:X.map(R=>({id:R.id,type:"function",function:{name:R.name,arguments:JSON.stringify(R.arguments)}}))});let Me=3,se=X,ue=X.filter(R=>R.name==="web.fetch");if(ue.length>Me){P(`[AIClient][${n}] Limiting web.fetch calls from ${ue.length} \u2192 ${Me} to prevent context overflow`);let R=ue.slice(0,Me);se=[...X.filter(Lt=>Lt.name!=="web.fetch"),...R];let Ce=ue.slice(Me);for(let Lt of Ce)E.push({role:"tool",tool_call_id:Lt.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ft=5e4,ve=0,K=[],W=!1,z=setInterval(()=>{W||K.push({delta:""})},500),fe=Date.now(),Ae,Y;try{if(se.length>=2)P(`[AIClient][${n}] stream() using parallel execution for ${se.length} tools`),Y=new Map,Ae=await this.toolOrchestrator.executeWithDependencies(se,async R=>{let J=Date.now(),Ce=await this.executeTool(R,d,i,$);return Y.set(R.id,Date.now()-J),Ce},5);else{P(`[AIClient][${n}] stream() executing single tool sequentially`),Y=new Map,Ae=new Map;for(let R of se){let J=Date.now(),Ce=await this.executeTool(R,d,i,$);Y.set(R.id,Date.now()-J),Ae.set(R.id,Ce)}}}finally{W=!0,clearInterval(z)}for(;K.length>0;)yield K.shift();await new Promise(R=>setTimeout(R,0)),y(`[AIClient][${n}] stream() tool batch completed in ${Date.now()-fe}ms`);for(let R of se){let J=Ae.get(R.id),Ce=typeof J=="string"?J:JSON.stringify(J),Lt=ft-ve,Ow=Y.get(R.id)??0,ia=Ce.startsWith("data:image/"),Le;ia?Le=Ce:ve+Ce.length>ft?(O(`[AIClient][${n}] Tool output budget exceeded (${ft} chars)`),Le=this.budgetTruncate(Ce,Lt)):typeof J=="string"&&J.length>this.toolResultMaxChars?Le=`${J.slice(0,this.toolResultMaxChars)}
416
+ [TRUNCATED tool result: ${J.length} chars]`:Le=Ce;let aa=typeof Le=="string"?Le:JSON.stringify(Le);ia||(ve+=aa.length),E.push({role:"tool",tool_call_id:R.id,content:Le}),yield{delta:"",tool_calls:[{...R,result:aa,duration:Ow}]}}y(`[AIClient][${n}] Round tool output size: ${ve} chars (budget: ${ft})`),Tt("debug")&&(y(`[AIClient][${n}] stream() after_tools messages=${E.length}`),kn(n,E))}}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,t){if(t?.blockAllTools)return P(`[AIClient] Mode "${t.displayName}" blocks all tools`),{request:e,requestToolMap:new Map};let o=this.buildRequestToolMap(e.requestTools),n=Array.from(o.values()).map(b=>this.requestToolToSchema(b)),s=o.size>0,i=t?.toolsConfig?{...this.toolsConfig,...t.toolsConfig}:this.toolsConfig,a=this.toolDefinitionsToSchemas(t?.customTools??[]),c=this.mergeSchemas(a,n);if(!i.enabled&&!s&&a.length===0)return y("[AIClient] Tools disabled and no request-scoped or mode tools"),{request:e,requestToolMap:o};let p=i;if(t?.toolSearch&&i.toolSearch&&(p={...i,toolSearch:{...i.toolSearch,...t.toolSearch.enabled!==void 0?{enabled:t.toolSearch.enabled}:{},...t.toolSearch.alwaysLoadedTools?{alwaysLoadedTools:t.toolSearch.alwaysLoadedTools}:{},...t.toolSearch.alwaysLoadedCategories?{alwaysLoadedCategories:t.toolSearch.alwaysLoadedCategories}:{}}},y(`[AIClient] Merged mode toolSearch config: enabled=${p.toolSearch?.enabled}, alwaysLoadedTools=${p.toolSearch?.alwaysLoadedTools?.length||0}`)),e.tools&&e.tools.length>0){if(!p.toolSearch?.enabled||!this.toolRegistry){y(`[AIClient] Request already has ${e.tools.length} tools`);let x=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(c)),C=x===e.tools?e:{...e,tools:x};return{request:this.injectRequestToolGuidance(C,x),requestToolMap:o}}let b=await this.toolRouter.resolve(e.messages,this.toolRegistry,p);if(y(`[AIClient] Resolved ${b.length} tools to send: ${b.map(x=>x.name).join(", ")||"none"}`),t&&b.length>0){let x=b.length;b=this.filterSchemasByMode(b,t);let C=x-b.length;C>0&&P(`[AIClient] Mode "${t.displayName}" filtered out ${C} tools`)}let T=new Set(e.tools.map(x=>x.function.name)),k=b.filter(x=>!T.has(x.name)).map(x=>({type:"function",function:{name:x.name,description:x.description,parameters:x.parameters}}));if(k.length===0){y(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`);let x=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(c)),C=x===e.tools?e:{...e,tools:x};return{request:this.injectRequestToolGuidance(C,x),requestToolMap:o}}let v={...e,tools:this.mergeToolCallRequests([...e.tools,...k],this.schemasToToolCallRequests(c))};return p.toolSearch?.enabled&&this.toolRegistry&&(v=this.injectToolSearchPrompt(v)),{request:this.injectRequestToolGuidance(v,v.tools),requestToolMap:o}}if(!this.toolRegistry){y("[AIClient] Tool registry not configured, skipping tool resolution");let b=this.schemasToToolCallRequests(c),T=b.length>0?{...e,tools:b}:e;return{request:this.injectRequestToolGuidance(T,b),requestToolMap:o}}let m=this.toolRegistry,d=await this.toolRouter.resolve(e.messages,m,p);if(y(`[AIClient] Resolved ${d.length} tools to send: ${d.map(b=>b.name).join(", ")||"none"}`),t&&d.length>0){let b=d.length;d=this.filterSchemasByMode(d,t);let T=b-d.length;T>0&&P(`[AIClient] Mode "${t.displayName}" filtered out ${T} tools`)}let g=this.schemasToToolCallRequests(this.mergeSchemas(d,c));if(g.length===0)return{request:e,requestToolMap:o};let w={...e,tools:g};return i.toolSearch?.enabled&&m&&(w=this.injectToolSearchPrompt(w)),{request:this.injectRequestToolGuidance(w,g),requestToolMap:o}}toolDefinitionsToSchemas(e){return e.map(t=>({name:t.name,displayName:t.displayName,description:t.description,parameters:t.parameters,category:t.category,...t.cacheable!==void 0&&{cacheable:t.cacheable},...t.annotations!==void 0&&{annotations:t.annotations}}))}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(`
417
417
  `))}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}
418
418
  ${s.join(`
419
419
 
420
- `)}`,a=e.messages.findIndex(l=>l.role==="system");if(a>=0){let l=e.messages.map((p,m)=>{if(m!==a)return p;let d=typeof p.content=="string"?p.content:"";return d.includes(n)?p:{...p,content:`${d}
420
+ `)}`,a=e.messages.findIndex(c=>c.role==="system");if(a>=0){let c=e.messages.map((p,m)=>{if(m!==a)return p;let d=typeof p.content=="string"?p.content:"";return d.includes(n)?p:{...p,content:`${d}
421
421
 
422
- ${i}`.trim()}});return{...e,messages:l}}return{...e,messages:[{role:"system",content:i},...e.messages]}}stripRequestTools(e){let{requestTools:t,mode:o,...n}=e;return n}resolveRequestMode(e){return e.mode===void 0?this.activeMode:e.mode===null?null:typeof e.mode=="string"?(L(`[AIClient] Unresolved mode name "${e.mode}" on request \u2014 falling back to active mode. Pass requests through Toolpack.generate()/stream() to resolve mode names.`),this.activeMode):e.mode}filterSchemasByMode(e,t){return e.filter(o=>{if(t.blockedTools.includes(o.name)||t.blockedToolCategories.includes(o.category))return!1;if(bt(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,t){if(!t||!t.systemPrompt)return y(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. mode=${t?.name}, systemPrompt=${t?.systemPrompt?.substring(0,50)}`),e;let o=t.systemPrompt;if(y(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${t.name}, length=${o.length}`),e.messages.some(s=>s.role==="system")){let s=e.messages.map(i=>{if(i.role==="system"){let a=typeof i.content=="string"?i.content:"";return{...i,content:`${o}
422
+ ${i}`.trim()}});return{...e,messages:c}}return{...e,messages:[{role:"system",content:i},...e.messages]}}stripRequestTools(e){let{requestTools:t,mode:o,...n}=e;return n}newRequestId(){return`${Date.now()}-${++this.requestSeq}`}resolveRequestMode(e){return e.mode===void 0?this.activeMode:e.mode===null?null:typeof e.mode=="string"?(O(`[AIClient] Unresolved mode name "${e.mode}" on request \u2014 falling back to active mode. Pass requests through Toolpack.generate()/stream() to resolve mode names.`),this.activeMode):e.mode}filterSchemasByMode(e,t){return e.filter(o=>{if(t.blockedTools.includes(o.name)||t.blockedToolCategories.includes(o.category))return!1;if(bt(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,t){if(!t||!t.systemPrompt)return y(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. mode=${t?.name}, systemPrompt=${t?.systemPrompt?.substring(0,50)}`),e;let o=t.systemPrompt;if(y(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${t.name}, length=${o.length}`),e.messages.some(s=>s.role==="system")){let s=e.messages.map(i=>{if(i.role==="system"){let a=typeof i.content=="string"?i.content:"";return{...i,content:`${o}
423
423
 
424
424
  ${a}`}}return i});return{...e,messages:s}}else return{...e,messages:[{role:"system",content:o},...e.messages]}}async injectModeRules(e,t){if(!t)return e;let o=await this.ruleLoader.loadForMode(t.name,t.rulesDir);if(!o)return e;if(y(`[AIClient] injectModeRules: Injecting rules for mode "${t.name}", length=${o.length}`),e.messages.some(s=>s.role==="system")){let s=e.messages.map(i=>{if(i.role==="system"){let a=typeof i.content=="string"?i.content:"";return{...i,content:`${a}
425
425
 
426
426
  ${o}`}}return i});return{...e,messages:s}}return{...e,messages:[{role:"system",content:o},...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}
427
427
 
428
- ${t}`}}return s});return{...e,messages:n}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectBaseAgentContext(e,t){let o=!0,n=!0,s,i=this.disableBaseContext;if(t?.baseContext===!1)return e;t?.baseContext&&(o=t.baseContext.includeWorkingDirectory!==!1,n=t.baseContext.includeToolCategories!==!1,s=t.baseContext.custom);let a=s||Da({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:i,includeWorkingDirectory:o,includeToolCategories:n});if(!a)return e;if(e.messages.some(p=>p.role==="system")){let p=e.messages.map(m=>{if(m.role==="system"){let d=typeof m.content=="string"?m.content:"";return{...m,content:`${a}
428
+ ${t}`}}return s});return{...e,messages:n}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectBaseAgentContext(e,t){let o=!0,n=!0,s,i=this.disableBaseContext;if(t?.baseContext===!1)return e;t?.baseContext&&(o=t.baseContext.includeWorkingDirectory!==!1,n=t.baseContext.includeToolCategories!==!1,s=t.baseContext.custom);let a=s||Sa({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:i,includeWorkingDirectory:o,includeToolCategories:n});if(!a)return e;if(e.messages.some(p=>p.role==="system")){let p=e.messages.map(m=>{if(m.role==="system"){let d=typeof m.content=="string"?m.content:"";return{...m,content:`${a}
429
429
 
430
- ${d}`}}return m});return{...e,messages:p}}else return{...e,messages:[{role:"system",content:a},...e.messages]}}injectToolSearchPrompt(e){if(!this.toolRegistry)return e;let t=e.messages.some(i=>i.role==="system"),o=this.toolsConfig.toolSearch?.alwaysLoadedTools??[],n="";if(o.length>0){let i=o.map(a=>{let l=this.toolRegistry?.get(a);return l?` - **${l.name}**: ${l.description}`:null}).filter(Boolean).join(`
430
+ ${d}`}}return m});return{...e,messages:p}}else return{...e,messages:[{role:"system",content:a},...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(`
431
431
  `);i&&(n=`
432
432
 
433
433
  You have these tools always available:
@@ -438,7 +438,7 @@ IMPORTANT: Tool Discovery Instructions
438
438
 
439
439
  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}
440
440
 
441
- ${ts(this.toolRegistry)}
441
+ ${Jr(this.toolRegistry)}
442
442
 
443
443
  When you need a tool:
444
444
  1. Check if it's in your current tool list
@@ -446,13 +446,13 @@ When you need a tool:
446
446
  3. After discovering tools, you can call them directly in subsequent turns
447
447
 
448
448
  NEVER guess or hallucinate tool names. ALWAYS use tool.search to discover tools you don't have.
449
- `.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}
449
+ `.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}
450
450
 
451
- ${s}`}}return a});return{...e,messages:i}}else return{...e,messages:[{role:"system",content:s},...e.messages]}}async executeTool(e,t,o){let n=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: ${A(e.arguments,500)}`);let s=t.get(e.name),i=s?void 0:this.toolRegistry?.get(e.name);if(!s&&!this.toolRegistry){let l="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:l,duration:Date.now()-n}),JSON.stringify({error:l})}if(bt(e.name)){let l=this.executeToolSearch(e.arguments,o),p=Date.now()-n;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof l=="string"?l.substring(0,200):JSON.stringify(l).substring(0,200),duration:p}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:l,duration:p,status:"success",timestamp:Date.now()}),l}let a=s||i;if(!a){L(`[AIClient] Tool '${e.name}' not found in registry`);let l=this.findSimilarToolName(e.name),p=l?`Tool '${e.name}' not found. Did you mean '${l}'? 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:p,duration:Date.now()-n}),JSON.stringify({error:p})}try{let l=e.arguments;if(i?.confirmation&&this.onToolConfirm&&!this.isBypassed(i)){this.emit("tool:confirmation_requested",{tool:i,args:l,level:i.confirmation.level,reason:i.confirmation.reason});let b=await this.onToolConfirm(i,l,{roundNumber:this.currentRound,conversationId:this.conversationId});if(this.emit("tool:confirmation_resolved",{tool:i,args:l,level:i.confirmation.level,reason:i.confirmation.reason,decision:b}),b.action==="deny"){let w=`[Execution denied by user${b.reason?": "+b.reason:""}]`,T=Date.now()-n;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:w,duration:T}),this.emit("tool:log",{id:e.id,name:e.name,arguments:l,result:w,duration:T,status:"success",timestamp:Date.now()}),w}b.action==="modify"&&(l=b.args)}let p={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:b=>P(`[Tool] ${b}`)},m=s?await s.execute(l):await a.execute(l,p),d=Date.now()-n;this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof m=="string"?m.startsWith("data:image/")?m:m.substring(0,200):JSON.stringify(m).substring(0,200),duration:d}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:m,duration:d,status:"success",timestamp:Date.now()});let g=typeof m=="string"?m.length:JSON.stringify(m).length;return P(`[AIClient] Tool ${e.name} executed successfully in ${d}ms result_len=${g}`),tt("debug")&&y(`[AIClient] Tool ${e.name} result_preview=${A(m,400)}`),typeof m=="string"?m:JSON.stringify(m)}catch(l){let p=Date.now()-n,m=l.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:m,duration:p}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:m}),duration:p,status:"error",timestamp:Date.now()}),pe(`[AIClient] Tool ${e.name} failed: ${A(m,300)}`),JSON.stringify({error:m})}}findSimilarToolName(e){if(!this.toolRegistry)return null;let t=this.toolRegistry.getAll(),o=e.replace(/_/g,".");if(t.some(l=>l.name===o))return o;let n=e.replace(/\./g,"_");if(t.some(l=>l.name===n))return n;let s=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(l=>l.name===s))return s;let i=null,a=1/0;for(let l of t){let p=this.levenshteinDistance(e.toLowerCase(),l.name.toLowerCase());p<=2&&p<a&&(a=p,i=l.name)}return i}levenshteinDistance(e,t){let o=[];for(let n=0;n<=t.length;n++)o[n]=[n];for(let n=0;n<=e.length;n++)o[0][n]=n;for(let n=1;n<=t.length;n++)for(let s=1;s<=e.length;s++)t.charAt(n-1)===e.charAt(s-1)?o[n][s]=o[n-1][s-1]:o[n][s]=Math.min(o[n-1][s-1]+1,o[n][s-1]+1,o[n-1][s]+1);return o[t.length][e.length]}executeToolSearch(e,t){let{query:o,category:n}=e,s=this.toolsConfig.toolSearch?.searchResultLimit??5,i=typeof n=="string"&&n.length>0?n:void 0,a=t===void 0?this.activeMode:t;if(a&&!(this.filterSchemasByMode([Ze()],a).length>0))return L("[AIClient] tool.search blocked by active mode"),JSON.stringify({query:o,found:0,tools:[],hint:"tool.search is not allowed in the current mode."});P(`[AIClient] Executing tool.search: query="${o}" category=${i||"all"} limit=${s}`);let l=a?Math.max(s*4,s):s,p=this.bm25Engine.search(o,{limit:l,category:i});if(a&&p.length>0){let d=this.filterSchemasByMode(p.map(T=>T.tool),a),g=new Set(d.map(T=>T.name)),b=p.length;p=p.filter(T=>g.has(T.toolName));let w=b-p.length;w>0&&y(`[AIClient] tool.search filtered out ${w} disallowed results for mode "${a.displayName}"`)}p.length>s&&(p=p.slice(0,s));let m=p.map(d=>d.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(o,m),y(`[AIClient] tool.search found ${p.length} tools: ${m.join(", ")||"none"}`),JSON.stringify({query:o,found:p.length,tools:p.map(d=>({name:d.tool.name,displayName:d.tool.displayName,description:d.tool.description,category:d.tool.category,parameters:d.tool.parameters,relevanceScore:Math.round(d.score*100)/100})),hint:p.length>0?`Found ${p.length} tools. You can now call any of these tools directly.`:`No tools found for "${o}". Try a different search term.`})}wrapError(e){return e instanceof j?e:new F(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}budgetTruncate(e,t){let o=`
452
- [Output truncated \u2014 round budget reached. Call the tool again with a narrower query to retrieve more.]`,s=t-o.length;return s>=100?e.slice(0,s)+o:"[Tool output omitted \u2014 round budget exhausted. Call the tool again with a narrower query.]"}};c();c();import Ja from"@anthropic-ai/sdk";import{zodOutputFormat as TT}from"@anthropic-ai/sdk/helpers/zod";c();se();var ee=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new O(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new O(`File deletion API is not supported by ${this.getDisplayName()}`)}async countTokens(e,t){return null}};se();S();var En=class extends ee{client;constructor(e,t){super(),this.client=new Ja({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new O("Anthropic uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"Anthropic"}async getModels(){return[{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:64e3},{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-6",displayName:"Claude Opus 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),n=o.system,s=o.userMessages,i={model:e.model,messages:s,system:n,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!1};e.tools&&e.tools.length>0?(i.tools=e.tools.map(b=>({name:this.sanitizeToolName(b.function.name),description:b.function.description,input_schema:b.function.parameters})),e.tool_choice==="required"?i.tool_choice={type:"any"}:e.tool_choice==="none"?delete i.tools:i.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&y(`[Anthropic][${t}] First tool: ${A(i.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] generate() request: model=${i.model}, messages=${i.messages.length}, tools=${i.tools?.length||0}, tool_choice=${i.tool_choice?.type??"unset"}`),Z(t,"Anthropic",i.messages);let a=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format;a&&(i.output_config={format:TT(e.response_format)});let p=a?await this.client.messages.parse(i,e.signal?{signal:e.signal}:void 0):await this.client.messages.create(i,e.signal?{signal:e.signal}:void 0),m=[],d=[];for(let b of p.content)b.type==="text"?m.push(b.text):b.type==="tool_use"&&d.push({id:b.id,name:this.restoreToolName(b.name,e.tools),arguments:b.input});y(`[Anthropic][${t}] Response finish_reason=${p.stop_reason} tool_calls=${d.length} content_preview=${A(m.join(""),200)}`);let g={content:m.length>0?m.join(""):null,usage:{prompt_tokens:p.usage.input_tokens,completion_tokens:p.usage.output_tokens,total_tokens:p.usage.input_tokens+p.usage.output_tokens},finish_reason:this.mapFinishReason(p.stop_reason),tool_calls:d.length>0?d:void 0,raw:p};return a&&p.parsed_output!==void 0&&(g.data=p.parsed_output),g}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),n={model:e.model,messages:o.userMessages,system:o.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(n.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?n.tool_choice={type:"any"}:e.tool_choice==="none"?delete n.tools:n.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${n.tools?.length||0} tools with tool_choice: ${n.tool_choice?.type||"unset"}`),n.tools&&n.tools.length>0&&y(`[Anthropic][${t}] First tool: ${A(n.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice?.type??"unset"}`),Z(t,"Anthropic",n.messages);let s=await this.client.messages.create(n,e.signal?{signal:e.signal}:void 0),i="",a="",l="",p=!1;for await(let m of s)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,i=m.content_block.id,a=m.content_block.name,l=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(l+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(y(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${a}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:i,name:this.restoreToolName(a,e.tools),arguments:JSON.parse(l||"{}")}]},p=!1),m.type==="message_stop"&&(Le(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new O("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(vt(),Jt));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(`
453
- `);a&&(o=a)}}else if(i.role==="tool"&&i.tool_call_id)n.push({role:"user",content:[{type:"tool_result",tool_use_id:i.tool_call_id,content:typeof i.content=="string"?i.content:JSON.stringify(i.content)}]});else if(i.role==="assistant"&&i.tool_calls&&i.tool_calls.length>0){let a=[];if(typeof i.content=="string"&&i.content)a.push({type:"text",text:i.content});else if(Array.isArray(i.content)){let l=i.content.filter(p=>typeof p=="object"&&p.type==="text").map(p=>p.text).join(`
454
- `);l&&a.push({type:"text",text:l})}for(let l of i.tool_calls)a.push({type:"tool_use",id:l.id,name:this.sanitizeToolName(l.function.name),input:typeof l.function.arguments=="string"?JSON.parse(l.function.arguments||"{}"):l.function.arguments});n.push({role:"assistant",content:a})}else{let a=[];typeof i.content=="string"?a=i.content:i.content!==null&&(a=(await Promise.all(i.content.map(async l=>{if(l.type==="text")return{type:"text",text:l.text};if(l.type==="image_url"){let p=l.image_url.url;if(p.startsWith("data:")){let m=p.match(/^data:(image\/\w+);base64,(.+)$/);if(m)return{type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}}return{type:"image",source:{type:"url",url:p}}}if(l.type==="image_data"||l.type==="image_file"){let{data:p,mimeType:m}=await s(l);return{type:"image",source:{type:"base64",media_type:m,data:p}}}return null}))).filter(Boolean)),n.push({role:i.role==="user"?"user":"assistant",content:a})}return{system:o,userMessages:n}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":e==="stop_sequence"?"stop":e}handleError(e){if(e instanceof Ja.APIError){let t=e.message;return e.status===401?new he(t,e):e.status===429?new re(t,void 0,e):e.status&&e.status>=400&&e.status<500?new O(t,e):new F(t,"ANTHROPIC_ERROR",e.status||500,e)}return new F("Unknown Anthropic error","UNKNOWN",500,e)}};c();import xT from"@anthropic-ai/vertex-sdk";se();S();var Dn=class extends ee{client;constructor(e={}){super(),this.name="anthropic-vertex";let t=e.projectId??process.env.ANTHROPIC_VERTEX_PROJECT_ID??process.env.GOOGLE_CLOUD_PROJECT,o=e.region??process.env.ANTHROPIC_VERTEX_REGION??"us-east5";this.client=new xT({projectId:t,region:o})}getDisplayName(){return"Anthropic (Vertex AI)"}async getModels(){return[{id:"claude-sonnet-4-5@20250929",displayName:"Claude Sonnet 4.5 (Vertex AI)",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-haiku-4-5@20251001",displayName:"Claude Haiku 4.5 (Vertex AI)",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-3-5-sonnet-v2@20241022",displayName:"Claude 3.5 Sonnet v2 (Vertex AI)",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2e5,maxOutputTokens:8192},{id:"claude-3-5-haiku@20241022",displayName:"Claude 3.5 Haiku (Vertex AI)",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2e5,maxOutputTokens:8192}]}async generate(e){try{let t=e.__toolpack_request_id||`anv-${Date.now()}`,{system:o,userMessages:n}=await this.toAnthropicMessages(e.messages),s={model:e.model,messages:n,system:o,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p};e.tools&&e.tools.length>0&&(s.tools=e.tools.map(p=>({name:this.sanitizeToolName(p.function.name),description:p.function.description,input_schema:p.function.parameters})),e.tool_choice==="required"?s.tool_choice={type:"any"}:e.tool_choice==="none"?delete s.tools:s.tool_choice={type:"auto"}),y(`[AnthropicVertex][${t}] generate() model=${s.model} messages=${s.messages.length} tools=${s.tools?.length??0}`),Z(t,"AnthropicVertex",s.messages);let i=await this.client.messages.create(s),a=[],l=[];for(let p of i.content)p.type==="text"&&a.push(p.text),p.type==="tool_use"&&l.push({id:p.id,name:this.restoreToolName(p.name,e.tools),arguments:p.input});return y(`[AnthropicVertex][${t}] Response finish_reason=${i.stop_reason} tool_calls=${l.length} content_preview=${A(a.join(""),200)}`),{content:a.length>0?a.join(""):null,usage:{prompt_tokens:i.usage.input_tokens,completion_tokens:i.usage.output_tokens,total_tokens:i.usage.input_tokens+i.usage.output_tokens},finish_reason:this.mapFinishReason(i.stop_reason),tool_calls:l.length>0?l:void 0,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`anv-str-${Date.now()}`,{system:o,userMessages:n}=await this.toAnthropicMessages(e.messages),s={model:e.model,messages:n,system:o,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0&&(s.tools=e.tools.map(d=>({name:this.sanitizeToolName(d.function.name),description:d.function.description,input_schema:d.function.parameters})),e.tool_choice==="required"?s.tool_choice={type:"any"}:e.tool_choice==="none"?delete s.tools:s.tool_choice={type:"auto"}),y(`[AnthropicVertex][${t}] stream() model=${s.model} messages=${s.messages.length} tools=${s.tools?.length??0}`);let i=await this.client.messages.create(s),a="",l="",p="",m=!1;for await(let d of i)d.type==="content_block_start"&&d.content_block?.type==="tool_use"&&(m=!0,a=d.content_block.id,l=d.content_block.name,p=""),d.type==="content_block_delta"&&(d.delta.type==="text_delta"?yield{delta:d.delta.text}:d.delta.type==="input_json_delta"&&m&&(p+=d.delta.partial_json)),d.type==="content_block_stop"&&m&&(yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:a,name:this.restoreToolName(l,e.tools),arguments:JSON.parse(p||"{}")}]},m=!1),d.type==="message_stop"&&(yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new O("Embeddings are not supported by the Anthropic API.")}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 toAnthropicMessages(e){let t,o=[];for(let n of e)if(n.role==="system")t=typeof n.content=="string"?n.content:"";else if(n.role==="tool"&&n.tool_call_id)o.push({role:"user",content:[{type:"tool_result",tool_use_id:n.tool_call_id,content:typeof n.content=="string"?n.content:JSON.stringify(n.content)}]});else if(n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0){let s=[];typeof n.content=="string"&&n.content&&s.push({type:"text",text:n.content});for(let i of n.tool_calls)s.push({type:"tool_use",id:i.id,name:this.sanitizeToolName(i.function.name),input:typeof i.function.arguments=="string"?JSON.parse(i.function.arguments||"{}"):i.function.arguments});o.push({role:"assistant",content:s})}else o.push({role:n.role==="user"?"user":"assistant",content:typeof n.content=="string"?n.content:""});return{system:t,userMessages:o}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":"stop"}handleError(e){let t=e?.message??String(e);return e?.status===401||e?.status===403?new he(t,e):e?.status===429?new re(t,void 0,e):e?.status>=400&&e?.status<500?new O(t,e):new F(t||"Anthropic Vertex error","ANTHROPIC_VERTEX_ERROR",e?.status??500,e)}};c();import{GoogleGenAI as vT}from"@google/genai";import{zodToJsonSchema as CT}from"zod-to-json-schema";se();S();var Mn=class r extends ee{ai;location;thinkingBudget;rawContentCache=new Map;static RAW_CONTENT_CACHE_MAX=500;constructor(e={}){super(),this.name="vertexai";let t=e.projectId??process.env.TOOLPACK_VERTEXAI_PROJECT??process.env.VERTEX_AI_PROJECT??process.env.GOOGLE_CLOUD_PROJECT;if(!t)throw new he("Vertex AI requires a GCP project ID. Pass projectId in config or set TOOLPACK_VERTEXAI_PROJECT / VERTEX_AI_PROJECT / GOOGLE_CLOUD_PROJECT.");this.location=e.location??process.env.TOOLPACK_VERTEXAI_LOCATION??process.env.VERTEX_AI_LOCATION??"us-central1",this.ai=new vT({vertexai:!0,project:t,location:this.location,...e.googleAuthOptions?{googleAuthOptions:e.googleAuthOptions}:{}}),this.thinkingBudget=e.thinkingBudget}getDisplayName(){return"Google Vertex AI"}async getModels(){return[{id:"gemini-3.5-flash",displayName:"Gemini 3.5 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!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},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.5-pro-preview-05-06",displayName:"Gemini 2.5 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.5-flash-preview-04-17",displayName:"Gemini 2.5 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.0-flash-001",displayName:"Gemini 2.0 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:8192},{id:"gemini-1.5-pro-002",displayName:"Gemini 1.5 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2097152,maxOutputTokens:8192},{id:"gemini-1.5-flash-002",displayName:"Gemini 1.5 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:8192}]}async generate(e){try{let t=e.__toolpack_request_id||`vtx-${Date.now()}`;y(`[VertexAI][${t}] generate() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),Z(t,"VertexAI",e.messages);let{model:o,config:n}=this.buildRequestParams(e),{history:s,lastUserMessage:i}=this.formatHistory(e.messages),a=i!==null?[...s,{role:"user",parts:typeof i=="string"?[{text:i}]:i}]:s,l=await this.ai.models.generateContent({model:o,contents:a,config:n}),{content:p,toolCalls:m,rawContent:d}=this.parseResponse(l,e.tools);if(m.length>0&&d){let g=m.map(b=>b.id).join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(g,d)}return y(`[VertexAI][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${A(p,200)}`),{content:p||null,usage:{prompt_tokens:l.usageMetadata?.promptTokenCount??0,completion_tokens:l.usageMetadata?.candidatesTokenCount??0,total_tokens:l.usageMetadata?.totalTokenCount??0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:l}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`vtx-str-${Date.now()}`;y(`[VertexAI][${t}] stream() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),Z(t,"VertexAI",e.messages);let{model:o,config:n}=this.buildRequestParams(e),{history:s,lastUserMessage:i}=this.formatHistory(e.messages),a=i!==null?[...s,{role:"user",parts:typeof i=="string"?[{text:i}]:i}]:s,l=await this.ai.models.generateContentStream({model:o,contents:a,config:n});for await(let p of l)for(let m of p.candidates??[])for(let d of m.content?.parts??[])if(d.functionCall){let g=d.functionCall;y(`[VertexAI][${t}] stream tool_call name=${g.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:this.restoreToolName(g.name,e.tools),arguments:g.args??{}}]}}else d.text&&(yield{delta:d.text})}catch(t){throw this.handleError(t)}}async embed(e){throw new O("Vertex AI embeddings are not supported by this adapter. Use the Gemini adapter (gemini provider) with text-embedding-004 instead.")}buildRequestParams(e){let t=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format,o={systemInstruction:this.extractSystemInstruction(e.messages),maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||t)&&!e.tools?.length?"application/json":"text/plain",...t&&!e.tools?.length?{responseSchema:this.sanitizeSchema(CT(e.response_format))}:{}};return e.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(n=>({name:this.sanitizeToolName(n.function.name),description:n.function.description,parameters:this.sanitizeSchema(n.function.parameters)}))}]),this.thinkingBudget!==void 0&&this.thinkingBudget!==0&&(o.thinkingConfig={thinkingBudget:this.thinkingBudget}),{model:e.model,config:o}}formatHistory(e){let t=e.filter(l=>l.role!=="system");if(t.length===0)return{history:[],lastUserMessage:""};let o=t[t.length-1],n=o.role==="tool"&&!!o.tool_call_id,i=(n?t:t.slice(0,-1)).map(l=>{if(l.role==="tool"&&l.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(l.name??l.tool_call_id),response:{name:this.sanitizeToolName(l.name??l.tool_call_id),content:typeof l.content=="string"?l.content:JSON.stringify(l.content)}}}]};if(l.role==="assistant"&&l.tool_calls&&l.tool_calls.length>0){let p=l.tool_calls.map(g=>g.id).join("|"),m=this.rawContentCache.get(p);if(m)return m;let d=[];typeof l.content=="string"&&l.content&&d.push({text:l.content});for(let g of l.tool_calls)d.push({functionCall:{name:this.sanitizeToolName(g.function.name),args:typeof g.function.arguments=="string"?JSON.parse(g.function.arguments||"{}"):g.function.arguments}});return{role:"model",parts:d}}return{role:l.role==="user"?"user":"model",parts:this.contentToParts(l.content)}}),a=[];for(let l of i){let p=a[a.length-1];l.role==="function"&&p?.role==="function"?p.parts.push(...l.parts):a.push(l)}return{history:a,lastUserMessage:n?null:this.contentToParts(o.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="",s=null;for(let i of e.candidates??[]){i.content&&(s=i.content);for(let a of i.content?.parts??[])if(a.text&&!a.thought&&(n+=a.text),a.functionCall){let l=a.functionCall;o.push({id:`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:this.restoreToolName(l.name,t),arguments:l.args??{}})}}return{content:n,toolCalls:o,rawContent:s}}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(`
455
- `)}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 re(t,void 0,e):e?.status===401||e?.status===403||t.includes("UNAUTHENTICATED")||t.includes("PERMISSION_DENIED")?new he(t,e):e?.status>=400&&e?.status<500?new O(t,e):new F(t||"Vertex AI Error","VERTEXAI_ERROR",e?.status??500,e)}};c();import{GoogleGenerativeAI as kT}from"@google/generative-ai";import{zodToJsonSchema as Va}from"zod-to-json-schema";se();S();var An=class extends ee{genAI;constructor(e){super(),this.genAI=new kT(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 O("Gemini uploadFile requires a filePath.");let n=await t.promises.readFile(e.filePath),s=o.basename(e.filePath),i=e.mimeType||"application/octet-stream",l=`https://generativelanguage.googleapis.com/upload/v1beta/files?key=${this.genAI.apiKey}`,p="----WebKitFormBoundary"+Math.random().toString(36).substring(2),m=JSON.stringify({file:{displayName:s}}),d=Buffer.concat([Buffer.from(`--${p}\r
451
+ ${s}`}}return a});return{...e,messages:i}}else return{...e,messages:[{role:"system",content:s},...e.messages]}}async executeTool(e,t,o,n=0){let s=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: ${D(e.arguments,500)}`);let i=t.get(e.name),a=i?void 0:o?.customTools?.find(m=>m.name===e.name),c=i||a?void 0:this.toolRegistry?.get(e.name);if(!i&&!a&&!this.toolRegistry){let m="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:m,duration:Date.now()-s}),JSON.stringify({error:m})}if(bt(e.name)){let m=this.executeToolSearch(e.arguments,o),d=Date.now()-s;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof m=="string"?m.substring(0,200):JSON.stringify(m).substring(0,200),duration:d}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:m,duration:d,status:"success",timestamp:Date.now()}),m}let p=i||a||c;if(!p){O(`[AIClient] Tool '${e.name}' not found in registry or mode`);let m=this.findSimilarToolName(e.name),d=m?`Tool '${e.name}' not found. Did you mean '${m}'? 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:d,duration:Date.now()-s}),JSON.stringify({error:d})}try{let m=e.arguments,d=a??c;if(d?.confirmation&&this.onToolConfirm&&!this.isBypassed(d)){this.emit("tool:confirmation_requested",{tool:d,args:m,level:d.confirmation.level,reason:d.confirmation.reason});let v=await this.onToolConfirm(d,m,{roundNumber:n,conversationId:this.conversationId});if(this.emit("tool:confirmation_resolved",{tool:d,args:m,level:d.confirmation.level,reason:d.confirmation.reason,decision:v}),v.action==="deny"){let x=`[Execution denied by user${v.reason?": "+v.reason:""}]`,C=Date.now()-s;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:x,duration:C}),this.emit("tool:log",{id:e.id,name:e.name,arguments:m,result:x,duration:C,status:"success",timestamp:Date.now()}),x}v.action==="modify"&&(m=v.args)}let g=o?.toolsConfig?.additionalConfigurations?{...this.toolsConfig?.additionalConfigurations,...o.toolsConfig.additionalConfigurations}:this.toolsConfig?.additionalConfigurations??{},w={workspaceRoot:process.cwd(),config:g,log:v=>P(`[Tool] ${v}`),processRegistry:this.toolRegistry?.runtimeContext?.processRegistry,githubTokenStore:this.toolRegistry?.runtimeContext?.githubTokenStore},b=await p.execute(m,w),T=Date.now()-s;this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof b=="string"?b.startsWith("data:image/")?b:b.substring(0,200):JSON.stringify(b).substring(0,200),duration:T}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:b,duration:T,status:"success",timestamp:Date.now()});let k=typeof b=="string"?b.length:JSON.stringify(b).length;return P(`[AIClient] Tool ${e.name} executed successfully in ${T}ms result_len=${k}`),Tt("debug")&&y(`[AIClient] Tool ${e.name} result_preview=${D(b,400)}`),typeof b=="string"?b:JSON.stringify(b)}catch(m){let d=Date.now()-s,g=m.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:g,duration:d}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:g}),duration:d,status:"error",timestamp:Date.now()}),me(`[AIClient] Tool ${e.name} failed: ${D(g,300)}`),JSON.stringify({error:g})}}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,t){let{query:o,category:n}=e,s=this.toolsConfig.toolSearch?.searchResultLimit??5,i=typeof n=="string"&&n.length>0?n:void 0,a=t===void 0?this.activeMode:t;if(a&&!(this.filterSchemasByMode([Ye()],a).length>0))return O("[AIClient] tool.search blocked by active mode"),JSON.stringify({query:o,found:0,tools:[],hint:"tool.search is not allowed in the current mode."});P(`[AIClient] Executing tool.search: query="${o}" category=${i||"all"} limit=${s}`);let c=a?Math.max(s*4,s):s,p=this.bm25Engine.search(o,{limit:c,category:i});if(a&&p.length>0){let d=this.filterSchemasByMode(p.map(T=>T.tool),a),g=new Set(d.map(T=>T.name)),w=p.length;p=p.filter(T=>g.has(T.toolName));let b=w-p.length;b>0&&y(`[AIClient] tool.search filtered out ${b} disallowed results for mode "${a.displayName}"`)}p.length>s&&(p=p.slice(0,s));let m=p.map(d=>d.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(o,m),y(`[AIClient] tool.search found ${p.length} tools: ${m.join(", ")||"none"}`),JSON.stringify({query:o,found:p.length,tools:p.map(d=>({name:d.tool.name,displayName:d.tool.displayName,description:d.tool.description,category:d.tool.category,parameters:d.tool.parameters,relevanceScore:Math.round(d.score*100)/100})),hint:p.length>0?`Found ${p.length} tools. You can now call any of these tools directly.`:`No tools found for "${o}". Try a different search term.`})}wrapError(e){return e instanceof N?e:new I(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}budgetTruncate(e,t){let o=`
452
+ [Output truncated \u2014 round budget reached. Call the tool again with a narrower query to retrieve more.]`,s=t-o.length;return s>=100?e.slice(0,s)+o:"[Tool output omitted \u2014 round budget exhausted. Call the tool again with a narrower query.]"}};l();l();import qa from"@anthropic-ai/sdk";import{zodOutputFormat as uT}from"@anthropic-ai/sdk/helpers/zod";l();ae();var ee=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new M(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new M(`File deletion API is not supported by ${this.getDisplayName()}`)}async countTokens(e,t){return null}};ae();S();var Pn=class extends ee{client;constructor(e,t){super(),this.client=new qa({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new M("Anthropic uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"Anthropic"}async getModels(){return[{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:64e3},{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-6",displayName:"Claude Opus 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(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(w=>({name:this.sanitizeToolName(w.function.name),description:w.function.description,input_schema:w.function.parameters})),e.tool_choice==="required"?i.tool_choice={type:"any"}:e.tool_choice==="none"?delete i.tools:i.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&y(`[Anthropic][${t}] First tool: ${D(i.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] generate() request: model=${i.model}, messages=${i.messages.length}, tools=${i.tools?.length||0}, tool_choice=${i.tool_choice?.type??"unset"}`),Z(t,"Anthropic",i.messages);let a=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format;a&&(i.output_config={format:uT(e.response_format)});let p=a?await this.client.messages.parse(i,e.signal?{signal:e.signal}:void 0):await this.client.messages.create(i,e.signal?{signal:e.signal}:void 0),m=[],d=[];for(let w of p.content)w.type==="text"?m.push(w.text):w.type==="tool_use"&&d.push({id:w.id,name:this.restoreToolName(w.name,e.tools),arguments:w.input});y(`[Anthropic][${t}] Response finish_reason=${p.stop_reason} tool_calls=${d.length} content_preview=${D(m.join(""),200)}`);let g={content:m.length>0?m.join(""):null,usage:{prompt_tokens:p.usage.input_tokens,completion_tokens:p.usage.output_tokens,total_tokens:p.usage.input_tokens+p.usage.output_tokens},finish_reason:this.mapFinishReason(p.stop_reason),tool_calls:d.length>0?d:void 0,raw:p};return a&&p.parsed_output!==void 0&&(g.data=p.parsed_output),g}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),n={model:e.model,messages:o.userMessages,system:o.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(n.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?n.tool_choice={type:"any"}:e.tool_choice==="none"?delete n.tools:n.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${n.tools?.length||0} tools with tool_choice: ${n.tool_choice?.type||"unset"}`),n.tools&&n.tools.length>0&&y(`[Anthropic][${t}] First tool: ${D(n.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice?.type??"unset"}`),Z(t,"Anthropic",n.messages);let s=await this.client.messages.create(n,e.signal?{signal:e.signal}:void 0),i="",a="",c="",p=!1;for await(let m of s)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,i=m.content_block.id,a=m.content_block.name,c=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(c+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(y(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${a}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:i,name:this.restoreToolName(a,e.tools),arguments:JSON.parse(c||"{}")}]},p=!1),m.type==="message_stop"&&(Fe(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new M("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(vt(),Gt));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(`
453
+ `);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(`
454
+ `);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 qa.APIError){let t=e.message;return e.status===401?new ge(t,e):e.status===429?new ie(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new I(t,"ANTHROPIC_ERROR",e.status||500,e)}return new I("Unknown Anthropic error","UNKNOWN",500,e)}};l();import fT from"@anthropic-ai/vertex-sdk";ae();S();var _n=class extends ee{client;constructor(e={}){super(),this.name="anthropic-vertex";let t=e.projectId??process.env.ANTHROPIC_VERTEX_PROJECT_ID??process.env.GOOGLE_CLOUD_PROJECT,o=e.region??process.env.ANTHROPIC_VERTEX_REGION??"us-east5";this.client=new fT({projectId:t,region:o})}getDisplayName(){return"Anthropic (Vertex AI)"}async getModels(){return[{id:"claude-sonnet-4-5@20250929",displayName:"Claude Sonnet 4.5 (Vertex AI)",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-haiku-4-5@20251001",displayName:"Claude Haiku 4.5 (Vertex AI)",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-3-5-sonnet-v2@20241022",displayName:"Claude 3.5 Sonnet v2 (Vertex AI)",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2e5,maxOutputTokens:8192},{id:"claude-3-5-haiku@20241022",displayName:"Claude 3.5 Haiku (Vertex AI)",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2e5,maxOutputTokens:8192}]}async generate(e){try{let t=e.__toolpack_request_id||`anv-${Date.now()}`,{system:o,userMessages:n}=await this.toAnthropicMessages(e.messages),s={model:e.model,messages:n,system:o,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p};e.tools&&e.tools.length>0&&(s.tools=e.tools.map(p=>({name:this.sanitizeToolName(p.function.name),description:p.function.description,input_schema:p.function.parameters})),e.tool_choice==="required"?s.tool_choice={type:"any"}:e.tool_choice==="none"?delete s.tools:s.tool_choice={type:"auto"}),y(`[AnthropicVertex][${t}] generate() model=${s.model} messages=${s.messages.length} tools=${s.tools?.length??0}`),Z(t,"AnthropicVertex",s.messages);let i=await this.client.messages.create(s),a=[],c=[];for(let p of i.content)p.type==="text"&&a.push(p.text),p.type==="tool_use"&&c.push({id:p.id,name:this.restoreToolName(p.name,e.tools),arguments:p.input});return y(`[AnthropicVertex][${t}] Response finish_reason=${i.stop_reason} tool_calls=${c.length} content_preview=${D(a.join(""),200)}`),{content:a.length>0?a.join(""):null,usage:{prompt_tokens:i.usage.input_tokens,completion_tokens:i.usage.output_tokens,total_tokens:i.usage.input_tokens+i.usage.output_tokens},finish_reason:this.mapFinishReason(i.stop_reason),tool_calls:c.length>0?c:void 0,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`anv-str-${Date.now()}`,{system:o,userMessages:n}=await this.toAnthropicMessages(e.messages),s={model:e.model,messages:n,system:o,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0&&(s.tools=e.tools.map(d=>({name:this.sanitizeToolName(d.function.name),description:d.function.description,input_schema:d.function.parameters})),e.tool_choice==="required"?s.tool_choice={type:"any"}:e.tool_choice==="none"?delete s.tools:s.tool_choice={type:"auto"}),y(`[AnthropicVertex][${t}] stream() model=${s.model} messages=${s.messages.length} tools=${s.tools?.length??0}`);let i=await this.client.messages.create(s),a="",c="",p="",m=!1;for await(let d of i)d.type==="content_block_start"&&d.content_block?.type==="tool_use"&&(m=!0,a=d.content_block.id,c=d.content_block.name,p=""),d.type==="content_block_delta"&&(d.delta.type==="text_delta"?yield{delta:d.delta.text}:d.delta.type==="input_json_delta"&&m&&(p+=d.delta.partial_json)),d.type==="content_block_stop"&&m&&(yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:a,name:this.restoreToolName(c,e.tools),arguments:JSON.parse(p||"{}")}]},m=!1),d.type==="message_stop"&&(yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new M("Embeddings are not supported by the Anthropic API.")}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 toAnthropicMessages(e){let t,o=[];for(let n of e)if(n.role==="system")t=typeof n.content=="string"?n.content:"";else if(n.role==="tool"&&n.tool_call_id)o.push({role:"user",content:[{type:"tool_result",tool_use_id:n.tool_call_id,content:typeof n.content=="string"?n.content:JSON.stringify(n.content)}]});else if(n.role==="assistant"&&n.tool_calls&&n.tool_calls.length>0){let s=[];typeof n.content=="string"&&n.content&&s.push({type:"text",text:n.content});for(let i of n.tool_calls)s.push({type:"tool_use",id:i.id,name:this.sanitizeToolName(i.function.name),input:typeof i.function.arguments=="string"?JSON.parse(i.function.arguments||"{}"):i.function.arguments});o.push({role:"assistant",content:s})}else o.push({role:n.role==="user"?"user":"assistant",content:typeof n.content=="string"?n.content:""});return{system:t,userMessages:o}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":"stop"}handleError(e){let t=e?.message??String(e);return e?.status===401||e?.status===403?new ge(t,e):e?.status===429?new ie(t,void 0,e):e?.status>=400&&e?.status<500?new M(t,e):new I(t||"Anthropic Vertex error","ANTHROPIC_VERTEX_ERROR",e?.status??500,e)}};l();import{GoogleGenAI as gT}from"@google/genai";import{zodToJsonSchema as hT}from"zod-to-json-schema";ae();S();var Rn=class r extends ee{ai;location;thinkingBudget;rawContentCache=new Map;static RAW_CONTENT_CACHE_MAX=500;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 ge("Vertex AI requires a GCP project ID. Pass projectId in config or set TOOLPACK_VERTEXAI_PROJECT / VERTEX_AI_PROJECT / GOOGLE_CLOUD_PROJECT.");this.location=e.location??process.env.TOOLPACK_VERTEXAI_LOCATION??process.env.VERTEX_AI_LOCATION??"us-central1",this.ai=new gT({vertexai:!0,project:t,location:this.location,...e.googleAuthOptions?{googleAuthOptions:e.googleAuthOptions}:{}}),this.thinkingBudget=e.thinkingBudget}getDisplayName(){return"Google Vertex AI"}async getModels(){return[{id:"gemini-3.5-flash",displayName:"Gemini 3.5 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!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},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.5-pro-preview-05-06",displayName:"Gemini 2.5 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.5-flash-preview-04-17",displayName:"Gemini 2.5 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-2.0-flash-001",displayName:"Gemini 2.0 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:8192},{id:"gemini-1.5-pro-002",displayName:"Gemini 1.5 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:2097152,maxOutputTokens:8192},{id:"gemini-1.5-flash-002",displayName:"Gemini 1.5 Flash",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0},contextWindow:1048576,maxOutputTokens:8192}]}async generate(e){try{let t=e.__toolpack_request_id||`vtx-${Date.now()}`;y(`[VertexAI][${t}] generate() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),Z(t,"VertexAI",e.messages);let{model:o,config:n}=this.buildRequestParams(e),{history:s,lastUserMessage:i}=this.formatHistory(e.messages),a=i!==null?[...s,{role:"user",parts:typeof i=="string"?[{text:i}]:i}]:s,c=await this.ai.models.generateContent({model:o,contents:a,config:n}),{content:p,toolCalls:m,rawContent:d}=this.parseResponse(c,e.tools);if(m.length>0&&d){let g=m.map(w=>w.id).join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(g,d)}return y(`[VertexAI][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${D(p,200)}`),{content:p||null,usage:{prompt_tokens:c.usageMetadata?.promptTokenCount??0,completion_tokens:c.usageMetadata?.candidatesTokenCount??0,total_tokens:c.usageMetadata?.totalTokenCount??0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:c}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`vtx-str-${Date.now()}`;y(`[VertexAI][${t}] stream() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),Z(t,"VertexAI",e.messages);let{model:o,config:n}=this.buildRequestParams(e),{history:s,lastUserMessage:i}=this.formatHistory(e.messages),a=i!==null?[...s,{role:"user",parts:typeof i=="string"?[{text:i}]:i}]:s,c=await this.ai.models.generateContentStream({model:o,contents:a,config:n});for await(let p of c)for(let m of p.candidates??[])for(let d of m.content?.parts??[])if(d.functionCall){let g=d.functionCall;y(`[VertexAI][${t}] stream tool_call name=${g.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:this.restoreToolName(g.name,e.tools),arguments:g.args??{}}]}}else d.text&&(yield{delta:d.text})}catch(t){throw this.handleError(t)}}async embed(e){throw new M("Vertex AI embeddings are not supported by this adapter. Use the Gemini adapter (gemini provider) with text-embedding-004 instead.")}buildRequestParams(e){let t=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format,o={systemInstruction:this.extractSystemInstruction(e.messages),maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||t)&&!e.tools?.length?"application/json":"text/plain",...t&&!e.tools?.length?{responseSchema:this.sanitizeSchema(hT(e.response_format))}:{}};return e.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(n=>({name:this.sanitizeToolName(n.function.name),description:n.function.description,parameters:this.sanitizeSchema(n.function.parameters)}))}]),this.thinkingBudget!==void 0&&this.thinkingBudget!==0&&(o.thinkingConfig={thinkingBudget:this.thinkingBudget}),{model:e.model,config:o}}formatHistory(e){let t=e.filter(c=>c.role!=="system");if(t.length===0)return{history:[],lastUserMessage:""};let o=t[t.length-1],n=o.role==="tool"&&!!o.tool_call_id,i=(n?t:t.slice(0,-1)).map(c=>{if(c.role==="tool"&&c.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(c.name??c.tool_call_id),response:{name:this.sanitizeToolName(c.name??c.tool_call_id),content:typeof c.content=="string"?c.content:JSON.stringify(c.content)}}}]};if(c.role==="assistant"&&c.tool_calls&&c.tool_calls.length>0){let p=c.tool_calls.map(g=>g.id).join("|"),m=this.rawContentCache.get(p);if(m)return m;let d=[];typeof c.content=="string"&&c.content&&d.push({text:c.content});for(let g of c.tool_calls)d.push({functionCall:{name:this.sanitizeToolName(g.function.name),args:typeof g.function.arguments=="string"?JSON.parse(g.function.arguments||"{}"):g.function.arguments}});return{role:"model",parts:d}}return{role:c.role==="user"?"user":"model",parts:this.contentToParts(c.content)}}),a=[];for(let c of i){let p=a[a.length-1];c.role==="function"&&p?.role==="function"?p.parts.push(...c.parts):a.push(c)}return{history:a,lastUserMessage:n?null:this.contentToParts(o.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="",s=null;for(let i of e.candidates??[]){i.content&&(s=i.content);for(let a of i.content?.parts??[])if(a.text&&!a.thought&&(n+=a.text),a.functionCall){let c=a.functionCall;o.push({id:`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:this.restoreToolName(c.name,t),arguments:c.args??{}})}}return{content:n,toolCalls:o,rawContent:s}}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(`
455
+ `)}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 ie(t,void 0,e):e?.status===401||e?.status===403||t.includes("UNAUTHENTICATED")||t.includes("PERMISSION_DENIED")?new ge(t,e):e?.status>=400&&e?.status<500?new M(t,e):new I(t||"Vertex AI Error","VERTEXAI_ERROR",e?.status??500,e)}};l();import{GoogleGenerativeAI as yT}from"@google/generative-ai";import{zodToJsonSchema as Wa}from"zod-to-json-schema";ae();S();var $n=class extends ee{genAI;constructor(e){super(),this.genAI=new yT(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 M("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}}),d=Buffer.concat([Buffer.from(`--${p}\r
456
456
  Content-Type: application/json\r
457
457
  \r
458
458
  ${m}\r
@@ -461,49 +461,49 @@ Content-Type: ${i}\r
461
461
  \r
462
462
  `),n,Buffer.from(`\r
463
463
  --${p}--\r
464
- `)]),g=await fetch(l,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:d});if(!g.ok){let w=await g.text();throw new Error(`Gemini file upload failed: ${g.status} ${w}`)}let b=await g.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(g=>({name:this.sanitizeToolName(g.function.name),description:g.function.description,parameters:this.sanitizeSchema(g.function.parameters)}))}],y(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&y(`[Gemini][${t}] First tool: ${A(e.tools[0],800)}`)):y(`[Gemini][${t}] NO TOOLS in request`),y(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(t,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format)&&!e.tools?.length?"application/json":"text/plain",...e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&!e.tools?.length?{responseSchema:this.sanitizeSchema(Va(e.response_format))}:{}}}).sendMessage(i)).response,m=[],d="";for(let g of p.candidates||[])for(let b of g.content?.parts||[])if(b.text&&(d+=b.text),b.functionCall){let w=b.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(w.name,e.tools),arguments:w.args||{}})}return y(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${A(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()}`;y(`[Gemini][${o}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&y(`[Gemini][${o}] First tool: ${A(e.tools[0],800)}`),Z(o,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),l=await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format)&&!e.tools?.length?"application/json":"text/plain",...e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&!e.tools?.length?{responseSchema:this.sanitizeSchema(Va(e.response_format))}:{}}}).sendMessageStream(i);for await(let p of l.stream){for(let m of p.candidates?.[0]?.content?.parts||[])m.functionCall?(y(`[Gemini][${o}] Stream finish_reason=tool_calls name=${m.functionCall.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.functionCall.name,e.tools),arguments:m.functionCall.args||{}}]}):m.text&&(yield{delta:m.text});try{let m=p.text();m&&!p.candidates?.[0]?.content?.parts?.some(d=>d.text)&&(yield{delta:m})}catch{}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=this.genAI.getGenerativeModel({model:e.model});return Array.isArray(e.input)?{embeddings:await Promise.all(e.input.map(async n=>(await t.embedContent(n)).embedding.values))}:{embeddings:[(await t.embedContent(e.input)).embedding.values]}}catch(t){throw this.handleError(t)}}extractSystemInstruction(e){let t=e.filter(o=>o.role==="system");if(t.length!==0)return t.map(o=>typeof o.content=="string"?o.content:o.content===null?"":o.content.map(n=>n.text).join(`
464
+ `)]),g=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:d});if(!g.ok){let b=await g.text();throw new Error(`Gemini file upload failed: ${g.status} ${b}`)}let w=await g.json();return{id:w.file?.name||w.name,url:w.file?.uri||w.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,o=`https://generativelanguage.googleapis.com/v1beta/${e}?key=${t}`,n=await fetch(o,{method:"DELETE"});if(!n.ok){let s=await n.text();throw new Error(`Gemini file deletion failed: ${n.status} ${s}`)}}catch(t){throw this.handleError(t)}}getDisplayName(){return"Google Gemini"}async getModels(){return[{id:"gemini-3.1-flash-lite-preview",displayName:"Gemini 3.1 Flash-Lite Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0?(o.tools=[{functionDeclarations:e.tools.map(g=>({name:this.sanitizeToolName(g.function.name),description:g.function.description,parameters:this.sanitizeSchema(g.function.parameters)}))}],y(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&y(`[Gemini][${t}] First tool: ${D(e.tools[0],800)}`)):y(`[Gemini][${t}] NO TOOLS in request`),y(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(t,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format)&&!e.tools?.length?"application/json":"text/plain",...e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&!e.tools?.length?{responseSchema:this.sanitizeSchema(Wa(e.response_format))}:{}}}).sendMessage(i)).response,m=[],d="";for(let g of p.candidates||[])for(let w of g.content?.parts||[])if(w.text&&(d+=w.text),w.functionCall){let b=w.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(b.name,e.tools),arguments:b.args||{}})}return y(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${D(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()}`;y(`[Gemini][${o}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&y(`[Gemini][${o}] First tool: ${D(e.tools[0],800)}`),Z(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"||e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format)&&!e.tools?.length?"application/json":"text/plain",...e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&!e.tools?.length?{responseSchema:this.sanitizeSchema(Wa(e.response_format))}:{}}}).sendMessageStream(i);for await(let p of c.stream){for(let m of p.candidates?.[0]?.content?.parts||[])m.functionCall?(y(`[Gemini][${o}] Stream finish_reason=tool_calls name=${m.functionCall.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.functionCall.name,e.tools),arguments:m.functionCall.args||{}}]}):m.text&&(yield{delta:m.text});try{let m=p.text();m&&!p.candidates?.[0]?.content?.parts?.some(d=>d.text)&&(yield{delta:m})}catch{}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=this.genAI.getGenerativeModel({model:e.model});return Array.isArray(e.input)?{embeddings:await Promise.all(e.input.map(async n=>(await t.embedContent(n)).embedding.values))}:{embeddings:[(await t.embedContent(e.input)).embedding.values]}}catch(t){throw this.handleError(t)}}extractSystemInstruction(e){let t=e.filter(o=>o.role==="system");if(t.length!==0)return t.map(o=>typeof o.content=="string"?o.content:o.content===null?"":o.content.map(n=>n.text).join(`
465
465
  `)).join(`
466
- `)}async formatHistory(e,t={}){let o=e.filter(d=>d.role!=="system");if(o.length===0)return{history:[],lastUserMessage:""};let n=o[o.length-1],s=o.slice(0,o.length-1),{normalizeImagePart:i}=await Promise.resolve().then(()=>(vt(),Jt)),a=async d=>typeof d=="string"?[{text:d}]:d===null?[]:(await Promise.all(d.map(async b=>{if(b.type==="text")return{text:b.text};if(b.type==="image_data"||b.type==="image_file"||b.type==="image_url")try{let{data:w,mimeType:T}=await i(b);return{inlineData:{mimeType:T,data:w}}}catch{return b.type==="image_url"?{text:`[Image: ${b.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),l=await Promise.all(s.map(async d=>{if(d.role==="tool"&&d.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(d.name||d.tool_call_id),response:{name:this.sanitizeToolName(d.name||d.tool_call_id),content:typeof d.content=="string"?d.content:JSON.stringify(d.content)}}}]};if(d.role==="assistant"&&d.tool_calls&&d.tool_calls.length>0){let g=[];if(typeof d.content=="string"&&d.content)g.push({text:d.content});else if(Array.isArray(d.content)){let b=d.content.filter(w=>typeof w=="object"&&w.type==="text").map(w=>w.text).join(`
467
- `);b&&g.push({text:b})}for(let b of d.tool_calls)g.push({functionCall:{name:this.sanitizeToolName(b.function.name),args:typeof b.function.arguments=="string"?JSON.parse(b.function.arguments||"{}"):b.function.arguments}});return{role:"model",parts:g}}return{role:d.role==="user"?"user":"model",parts:await a(d.content)}})),p=[];for(let d of l){let g=p[p.length-1];d.role==="function"&&g?.role==="function"?g.parts.push(...d.parts):p.push(d)}let m=typeof n.content=="string"?n.content:await a(n.content);return{history:p,lastUserMessage:m}}handleError(e){return e.status===429?new re(e.message,void 0,e):e.status>=400&&e.status<500?new O(e.message,e):e.message&&e.message.includes("API key")?new he(e.message,e):new F(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};c();se();import*as Fe from"fs";import*as ss from"path";var Qa="toolpack.config.json",Nn=new Map;async function Xa(r){for(;Nn.has(r);)await Nn.get(r);let e,t=new Promise(o=>{e=o});return Nn.set(r,t),()=>{Nn.delete(r),e()}}function ot(r){if(r&&Fe.existsSync(r))return r;let e=ss.join(process.cwd(),Qa);return Fe.existsSync(e)?e:null}function Qt(r){if(!r)return null;try{let e=Fe.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}var Vt=null;function is(r){if(Vt)return Vt;let e=r||ot();return Vt=Qt(e)||{},Vt}function as(){Vt=null}function ST(r){return(is(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function On(r){return is(r).ollama?.baseUrl||"http://localhost:11434"}async function PT(r){let{type:e,value:t,configPath:o}=r,n=o||ot();n||(n=ss.join(process.cwd(),Qa));let s=await Xa(n);try{let i=Qt(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 j(`Failed to write bypass rule to config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}as()}finally{s()}}async function _T(r){let{type:e,value:t,configPath:o}=r,n=o||ot();if(!n)return;let s=await Xa(n);try{let i=Qt(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 j(`Failed to remove bypass rule from config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}as()}finally{s()}}c();c();import{zodToJsonSchema as Za}from"zod-to-json-schema";se();S();c();import Ya from"http";function Re(r,e,t,o,n=12e4){return new Promise((s,i)=>{let a=new URL(e,r),l={hostname:a.hostname,port:a.port,path:a.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:n},p=Ya.request(l,m=>{let d=[];m.on("data",g=>d.push(g)),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 ls(r,e,t,o=12e4,n){let s,i=!1;return n&&n.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let l=new URL(e,r),p={hostname:l.hostname,port:l.port,path:l.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},m=await new Promise((g,b)=>{s=Ya.request(p,g),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 g="";for await(let b of m)g+=b.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${g}`)}let d="";for await(let g of m){if(i)break;let b=g.toString();if(d+=b,d.includes('"error"'))try{let T=JSON.parse(d.trim());if(T.error)throw new Error(`Ollama: ${T.error}`)}catch(T){if(T.message.startsWith("Ollama:"))throw T}let w=d.split(`
468
- `);d=w.pop()||"";for(let T of w)T.trim()&&(yield T)}d.trim()&&!i&&(yield d.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var nt=class extends ee{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 O(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
469
- Available models: ${e.map(n=>n.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await Re(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 Xe(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await Re(this.baseUrl,"/api/tags","GET",void 0,3e3),!0}catch{return!1}}async isModelAvailable(e){try{let t=await this.listModels(),o=(e||this.config.model).toLowerCase(),n=o.split(":")[0];return t.some(s=>s.name.split(":")[0].toLowerCase()===n||s.name.toLowerCase()===o)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await Promise.all(e.messages.map(i=>this.toOllamaMessage(i,e.mediaOptions))),n=e.model||this.config.model,s={model:n,messages:o,stream:!1,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=Za(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] generate() request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(t,"Ollama",e.messages);try{let i=await Re(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 y(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${l.length} content_preview=${A(p.content,200)}`),p}catch(i){throw i instanceof F?i:new Xe(`Failed to generate with Ollama model "${n}": ${i.message}`,i)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),n=e.model||this.config.model,s={model:n,messages:o,stream:!0,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=Za(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] Stream request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(t,"Ollama",e.messages);let{stream:i}=ls(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||{}}));y(`[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){Le(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new Xe(`Stream failed for Ollama model "${n}": ${a.message}`,a)}}async embed(e){let t=e.__toolpack_request_id||`emb-${Date.now()}`,o=typeof e.input=="string"?[e.input]:e.input,n=e.model||this.config.model;y(`[Ollama][${t}] Embedding request: model=${n}, inputs=${o.length}`);try{let s=await Re(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 Xe(`Embedding failed for Ollama model "${n}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(vt(),Jt));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+`
470
- `;else if(a.type==="image_url"||a.type==="image_data"||a.type==="image_file")try{let{data:l}=await s(a);n.push(l)}catch{a.type==="image_url"?o+=`[Image: ${a.image_url.url}]
466
+ `)}async formatHistory(e,t={}){let o=e.filter(d=>d.role!=="system");if(o.length===0)return{history:[],lastUserMessage:""};let n=o[o.length-1],s=o.slice(0,o.length-1),{normalizeImagePart:i}=await Promise.resolve().then(()=>(vt(),Gt)),a=async d=>typeof d=="string"?[{text:d}]:d===null?[]:(await Promise.all(d.map(async w=>{if(w.type==="text")return{text:w.text};if(w.type==="image_data"||w.type==="image_file"||w.type==="image_url")try{let{data:b,mimeType:T}=await i(w);return{inlineData:{mimeType:T,data:b}}}catch{return w.type==="image_url"?{text:`[Image: ${w.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),c=await Promise.all(s.map(async d=>{if(d.role==="tool"&&d.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(d.name||d.tool_call_id),response:{name:this.sanitizeToolName(d.name||d.tool_call_id),content:typeof d.content=="string"?d.content:JSON.stringify(d.content)}}}]};if(d.role==="assistant"&&d.tool_calls&&d.tool_calls.length>0){let g=[];if(typeof d.content=="string"&&d.content)g.push({text:d.content});else if(Array.isArray(d.content)){let w=d.content.filter(b=>typeof b=="object"&&b.type==="text").map(b=>b.text).join(`
467
+ `);w&&g.push({text:w})}for(let w of d.tool_calls)g.push({functionCall:{name:this.sanitizeToolName(w.function.name),args:typeof w.function.arguments=="string"?JSON.parse(w.function.arguments||"{}"):w.function.arguments}});return{role:"model",parts:g}}return{role:d.role==="user"?"user":"model",parts:await a(d.content)}})),p=[];for(let d of c){let g=p[p.length-1];d.role==="function"&&g?.role==="function"?g.parts.push(...d.parts):p.push(d)}let m=typeof n.content=="string"?n.content:await a(n.content);return{history:p,lastUserMessage:m}}handleError(e){return e.status===429?new ie(e.message,void 0,e):e.status>=400&&e.status<500?new M(e.message,e):e.message&&e.message.includes("API key")?new ge(e.message,e):new I(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();ae();import*as qe from"fs";import*as Yr from"path";var Ua="toolpack.config.json",En=new Map;async function Ga(r){for(;En.has(r);)await En.get(r);let e,t=new Promise(o=>{e=o});return En.set(r,t),()=>{En.delete(r),e()}}function tt(r){if(r&&qe.existsSync(r))return r;let e=Yr.join(process.cwd(),Ua);return qe.existsSync(e)?e:null}function Bt(r){if(!r)return null;try{let e=qe.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function Zr(r){let e=r||tt();return Bt(e)||{}}function bT(){}function wT(r){return(Zr(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function Dn(r){return Zr(r).ollama?.baseUrl||"http://localhost:11434"}async function TT(r){let{type:e,value:t,configPath:o}=r,n=o||tt();n||(n=Yr.join(process.cwd(),Ua));let s=await Ga(n);try{let i=Bt(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{qe.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")}}finally{s()}}async function xT(r){let{type:e,value:t,configPath:o}=r,n=o||tt();if(!n)return;let s=await Ga(n);try{let i=Bt(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{qe.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")}}finally{s()}}l();l();import{zodToJsonSchema as za}from"zod-to-json-schema";ae();S();l();import Ba from"http";function Re(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=Ba.request(c,m=>{let d=[];m.on("data",g=>d.push(g)),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 es(r,e,t,o=12e4,n){let s,i=!1;return n&&n.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let c=new URL(e,r),p={hostname:c.hostname,port:c.port,path:c.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},m=await new Promise((g,w)=>{s=Ba.request(p,g),s.on("error",w),s.on("timeout",()=>{s.destroy(),w(new Error("Stream request timed out"))}),s.write(JSON.stringify(t)),s.end()});if(m.statusCode&&m.statusCode>=400){let g="";for await(let w of m)g+=w.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${g}`)}let d="";for await(let g of m){if(i)break;let w=g.toString();if(d+=w,d.includes('"error"'))try{let T=JSON.parse(d.trim());if(T.error)throw new Error(`Ollama: ${T.error}`)}catch(T){if(T.message.startsWith("Ollama:"))throw T}let b=d.split(`
468
+ `);d=b.pop()||"";for(let T of b)T.trim()&&(yield T)}d.trim()&&!i&&(yield d.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var ot=class extends ee{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 M(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
469
+ Available models: ${e.map(n=>n.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await Re(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new I(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof I?e:new Qe(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await Re(this.baseUrl,"/api/tags","GET",void 0,3e3),!0}catch{return!1}}async isModelAvailable(e){try{let t=await this.listModels(),o=(e||this.config.model).toLowerCase(),n=o.split(":")[0];return t.some(s=>s.name.split(":")[0].toLowerCase()===n||s.name.toLowerCase()===o)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await Promise.all(e.messages.map(i=>this.toOllamaMessage(i,e.mediaOptions))),n=e.model||this.config.model,s={model:n,messages:o,stream:!1,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=za(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${D(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] generate() request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(t,"Ollama",e.messages);try{let i=await Re(this.baseUrl,"/api/chat","POST",s,this.timeout);if(i.status!==200)throw this.handleHttpError(i.status,i.body);let a=JSON.parse(i.body),c=[];if(a.message?.tool_calls)for(let m of a.message.tool_calls)c.push({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}});let p={content:a.message?.content||null,usage:a.prompt_eval_count!=null?{prompt_tokens:a.prompt_eval_count||0,completion_tokens:a.eval_count||0,total_tokens:(a.prompt_eval_count||0)+(a.eval_count||0)}:void 0,finish_reason:c.length>0?"tool_calls":a.done?"stop":void 0,tool_calls:c.length>0?c:void 0,raw:a};return y(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${D(p.content,200)}`),p}catch(i){throw i instanceof I?i:new Qe(`Failed to generate with Ollama model "${n}": ${i.message}`,i)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),n=e.model||this.config.model,s={model:n,messages:o,stream:!0,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=za(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${D(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] Stream request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(t,"Ollama",e.messages);let{stream:i}=es(this.baseUrl,"/api/chat",s,this.timeout,e.signal);try{for await(let a of i)try{let c=JSON.parse(a);if(c.message?.content){let p=c.message.tool_calls&&c.message.tool_calls.length>0;yield{delta:c.message.content,finish_reason:c.done&&!p?"stop":void 0,usage:c.done&&c.prompt_eval_count!=null?{prompt_tokens:c.prompt_eval_count||0,completion_tokens:c.eval_count||0,total_tokens:(c.prompt_eval_count||0)+(c.eval_count||0)}:void 0}}if(c.message?.tool_calls&&c.message.tool_calls.length>0){let p=c.message.tool_calls.map(m=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}}));y(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(c.done&&!c.message?.content&&!c.message?.tool_calls){Fe(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new Qe(`Stream failed for Ollama model "${n}": ${a.message}`,a)}}async embed(e){let t=e.__toolpack_request_id||`emb-${Date.now()}`,o=typeof e.input=="string"?[e.input]:e.input,n=e.model||this.config.model;y(`[Ollama][${t}] Embedding request: model=${n}, inputs=${o.length}`);try{let s=await Re(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 I?s:new Qe(`Embedding failed for Ollama model "${n}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(vt(),Gt));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+`
470
+ `;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}]
471
471
  `:o+=`[Unresolvable Image]
472
- `}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 O(`Model not found: ${o}`):new F(o,"OLLAMA_ERROR",e)}};c();var Xt=class extends ee{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 Re(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 nt({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 Re(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(a.status===200){let p=(JSON.parse(a.body).details?.families||[]).map(m=>m.toLowerCase());o=p.some(m=>["clip","mllama"].includes(m)),n=p.some(m=>m.includes("bert")||m.includes("nomic"))}}catch{}t=await this.probeToolSupport(e.name);let s=e.name.toLowerCase();o||(o=["llava","vision","bakllava","moondream"].some(l=>s.includes(l))),n||(n=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(l=>s.includes(l)));let i={toolCalling:t,vision:o,embeddings:n};return this.capabilityCache.set(e.name,i),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:n,vision:o}}}async probeToolSupport(e){try{let t=await Re(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 cs=[{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 RT(){return cs[0].model}function $T(r){let e=r.toLowerCase();return cs.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function ET(){return[...cs]}c();import el from"openai";import{zodResponseFormat as tl}from"openai/helpers/zod";se();S();var Ct=class extends ee{client;constructor(e,t){super(),this.client=new el({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 O("OpenAI uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"OpenAI"}async getModels(){return[{id:"gpt-4.1-mini",displayName:"GPT-4.1 Mini",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"low"},{id:"gpt-4.1",displayName:"GPT-4.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"medium"},{id:"gpt-5.1",displayName:"GPT-5.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"medium"},{id:"gpt-5.2",displayName:"GPT-5.2",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4",displayName:"GPT-5.4",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"extended",costTier:"premium"}]}sanitizeToolName(e){return e.replace(/\./g,"_")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,n={messages:await Promise.all(e.messages.map(d=>this.toOpenAIMessage(d,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format?tl(e.response_format,"structured_output"):void 0,stream:!1},s=new Map;e.tools&&e.tools.length>0&&(n.tools=e.tools.map(d=>{let g=this.sanitizeToolName(d.function.name);return s.set(g,d.function.name),{type:"function",function:{name:g,description:d.function.description,parameters:d.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),y(`[OpenAI][${t}] First tool: ${A(n.tools[0],800)}`)),y(`[OpenAI][${t}] Request params: ${A({model:n.model,messages_count:n.messages.length,has_tools:!!n.tools,tools_count:n.tools?.length,tool_choice:n.tool_choice},800)}`),Z(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0);Le(`[OpenAI][${t}] Raw completion: ${JSON.stringify(i)}`);let a=i.choices[0].message;y(`[OpenAI][${t}] Response: finish_reason=${i.choices[0].finish_reason}`),y(`[OpenAI][${t}] Response has tool_calls: ${!!a.tool_calls}, count: ${a.tool_calls?.length||0}`),y(`[OpenAI][${t}] Response content: ${JSON.stringify(a.content)}`),a.content&&y(`[OpenAI][${t}] Response content preview: ${A(a.content,200)}`);let l=i.choices[0],p,m=l.message.tool_calls;return m&&m.length>0&&(p=m.map(d=>({id:d.id,name:s.get(d.function.name)||d.function.name,arguments:JSON.parse(d.function.arguments)}))),{content:l.message.content,usage:i.usage?{prompt_tokens:i.usage.prompt_tokens,completion_tokens:i.usage.completion_tokens,total_tokens:i.usage.total_tokens}:void 0,finish_reason:l.finish_reason,tool_calls:p,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,n={messages:await Promise.all(e.messages.map(l=>this.toOpenAIMessage(l,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format?tl(e.response_format,"structured_output"):void 0,stream:!0},s=new Map;e.tools&&e.tools.length>0?(n.tools=e.tools.map(l=>{let p=this.sanitizeToolName(l.function.name);return s.set(p,l.function.name),{type:"function",function:{name:p,description:l.function.description,parameters:l.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),y(`[OpenAI][${t}] First tool: ${A(n.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice??"unset"}`),Z(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0),a=new Map;for await(let l of i){let p=l.choices[0];if(p.finish_reason&&Le(`[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 g=a.get(d);m.id&&(g.id=m.id),m.function?.name&&(g.name=m.function.name),m.function?.arguments&&(g.args+=m.function.arguments),Le(`[OpenAI][${t}] tool_call_delta idx=${d} id=${m.id||g.id||""} name=${m.function?.name||g.name||""} args_delta=${A(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage: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||"{}")}));y(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(d=>d.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,o=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:o.data.map(n=>n.embedding),usage:o.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(s=>({id:s.id,type:"function",function:{name:this.sanitizeToolName(s.function.name),arguments:s.function.arguments}}))};if(typeof e.content=="string")return{role:e.role,content:e.content};if(e.content===null||e.content===void 0)return{role:e.role,content:""};let{normalizeImagePart:o}=await Promise.resolve().then(()=>(vt(),Jt)),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 el.APIError){let t=e.message;return e.status===401?new he(t,e):e.status===429?new re(t,void 0,e):e.status&&e.status>=400&&e.status<500?new O(t,e):new F(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new F("Unknown error","UNKNOWN",500,e)}};c();var ol="https://openrouter.ai/api/v1",In=class extends Ct{name="openrouter";_apiKey;constructor(e,t={}){super(e,ol),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(`${ol}/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"}};vt();c();zt();c();zt();var vn=class{tools=new Map;projects=new Map;config=ce;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),o=new Set,n=[];for(let s of[...e,...t])o.has(s.name)||(o.add(s.name),n.push(s));return n}getSchemas(e){return(e?e.map(o=>this.tools.get(o)).filter(Boolean):this.getEnabled()).map(o=>({name:o.name,displayName:o.displayName,description:o.description,parameters:o.parameters,category:o.category,...o.cacheable!==void 0&&{cacheable:o.cacheable},...o.annotations!==void 0&&{annotations:o.annotations}}))}getByNames(e){return e.map(t=>this.tools.get(t)).filter(Boolean)}getByCategories(e){let t=new Set(e);return Array.from(this.tools.values()).filter(o=>t.has(o.category))}getCategories(){let e=new Set;for(let t of this.tools.values())e.add(t.category);return Array.from(e)}getAll(){return Array.from(this.tools.values())}setConfig(e){this.config=e}getConfig(){return this.config}get size(){return this.tools.size}async validateDependencies(e){let t=e.dependencies;if(!t||Object.keys(t).length===0)return[];let o=[];for(let n of Object.keys(t))try{await import(n)}catch{o.push(n)}return o}async loadProject(e){let t=await this.validateDependencies(e);if(t.length>0)throw new Error(`Tool project "${e.manifest.name}" has missing dependencies: ${t.join(", ")}. Install them with: npm install ${t.join(" ")}`);this.projects.set(e.manifest.name,e);for(let o of e.tools)this.register(o)}async loadProjects(e){for(let t of e)await this.loadProject(t)}getProject(e){return this.projects.get(e)}getProjects(){return Array.from(this.projects.values())}getProjectNames(){return Array.from(this.projects.keys())}async loadBuiltIn(){let{fsToolsProject:e}=await Promise.resolve().then(()=>(Rs(),hp)),{execToolsProject:t}=await Promise.resolve().then(()=>(js(),gm)),{systemToolsProject:o}=await Promise.resolve().then(()=>(Bs(),Qm)),{httpToolsProject:n}=await Promise.resolve().then(()=>(Qs(),Ad)),{githubToolsProject:s}=await Promise.resolve().then(()=>(ai(),Fu)),{webToolsProject:i}=await Promise.resolve().then(()=>(Ti(),lg)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Li(),Xh)),{gitToolsProject:l}=await Promise.resolve().then(()=>(Fi(),Ey)),{diffToolsProject:p}=await Promise.resolve().then(()=>(qi(),zy)),{dbToolsProject:m}=await Promise.resolve().then(()=>(Ui(),bb)),{cloudToolsProject:d}=await Promise.resolve().then(()=>(Gi(),$b)),{slackToolsProject:g}=await Promise.resolve().then(()=>(Qi(),uw)),{k8sToolsProject:b}=await Promise.resolve().then(()=>(Xi(),yw));await this.loadProjects([e,t,o,n,s,i,a,l,p,m,d,g,b])}};pi();c();S();function WC(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}}Gt();Rs();js();Bs();Qs();ai();Ti();Li();Fi();qi();Ui();Gi();Xi();Qi();c();c();S();import{spawn as UC}from"child_process";import{EventEmitter as GC}from"events";var jr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},Ne=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},Cn=class extends GC{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 Ne("Client is shutting down");if(this.buffer="",this.process=UC(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new Ne("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 Ne(`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(`
473
- `))!==-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 Ne("Client not connected");let s=this.nextId++,i=n??this.defaultTimeoutMs,a={jsonrpc:"2.0",id:s,method:t,params:o};return new Promise((l,p)=>{let m;i>0&&(m=setTimeout(()=>{let d=this.messageQueue.get(s);d&&(this.messageQueue.delete(s),d.reject(new jr(t,i)))},i)),this.messageQueue.set(s,{resolve:l,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
474
- `)}catch(d){m&&clearTimeout(m),this.messageQueue.delete(s),p(d)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new Ne("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 Ne("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()}};S();var Lr=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 Cn({...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 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 Yi(r){let e=new Lr(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 Zi(r){"mcpManager"in r&&await r.mcpManager.disconnectAll()}c();import*as Q from"fs/promises";import*as ie from"path";function ta(r){let e={},t=r.match(/^---\n([\s\S]*?)\n---/);if(!t||!t[1])return e;for(let o of t[1].split(`
475
- `)){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 oa(r){let e=r.match(/\[(.*)\]/);return!e||!e[1]?[]:e[1].split(",").map(t=>t.trim().replace(/"/g,"")).filter(Boolean)}function ea(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(`
476
- `).filter(n=>n.startsWith("- "))){let n=o.match(/^- "(.*)"/);n&&n[1]&&e.push(n[1])}return e}function pt(r,e){let t=r.match(new RegExp(`## ${e}\\n\\n([\\s\\S]*?)(?=\\n## |$)`));return t&&t[1]?t[1].trim():""}async function bw(r,e){async function t(o){let n;try{n=await Q.readdir(o)}catch{return null}for(let s of n){let i=ie.join(o,s),a;try{a=await Q.stat(i)}catch{continue}if(a.isDirectory()){let l=await t(i);if(l)return l}else if(a.isFile()&&s===`${e}.skill.md`)return i}return null}return t(r)}async function BC(r){let e=[];async function t(o){let n;try{n=await Q.readdir(o)}catch{return}for(let s of n){let i=ie.join(o,s),a;try{a=await Q.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function zC(r){let{name:e,title:t,description:o,triggers:n,instructions:s,examples:i,tags:a}=r,l=new Date().toISOString(),p=a&&a.length>0?a.map(d=>`"${d}"`).join(", "):"",m=["---",`name: ${e}`,`title: ${t}`,"version: 1.0.0",`updated: ${l}`,`tags: [${p}]`,"---","","## Description","",o,"","## Triggers","",n.map(d=>`- "${d}"`).join(`
472
+ `}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 M(`Model not found: ${o}`):new I(o,"OLLAMA_ERROR",e)}};l();var zt=class extends ee{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 Re(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 ot({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 Re(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 Re(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 ts=[{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 vT(){return ts[0].model}function CT(r){let e=r.toLowerCase();return ts.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function kT(){return[...ts]}l();import Ha from"openai";import{zodResponseFormat as Ka}from"openai/helpers/zod";ae();S();var Ct=class extends ee{client;constructor(e,t){super(),this.client=new Ha({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new M("OpenAI uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"OpenAI"}async getModels(){return[{id:"gpt-4.1-mini",displayName:"GPT-4.1 Mini",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"low"},{id:"gpt-4.1",displayName:"GPT-4.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"medium"},{id:"gpt-5.1",displayName:"GPT-5.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"medium"},{id:"gpt-5.2",displayName:"GPT-5.2",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4",displayName:"GPT-5.4",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"extended",costTier:"premium"}]}sanitizeToolName(e){return e.replace(/\./g,"_")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,n={messages:await Promise.all(e.messages.map(d=>this.toOpenAIMessage(d,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format?Ka(e.response_format,"structured_output"):void 0,stream:!1},s=new Map;e.tools&&e.tools.length>0&&(n.tools=e.tools.map(d=>{let g=this.sanitizeToolName(d.function.name);return s.set(g,d.function.name),{type:"function",function:{name:g,description:d.function.description,parameters:d.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),y(`[OpenAI][${t}] First tool: ${D(n.tools[0],800)}`)),y(`[OpenAI][${t}] Request params: ${D({model:n.model,messages_count:n.messages.length,has_tools:!!n.tools,tools_count:n.tools?.length,tool_choice:n.tool_choice},800)}`),Z(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0);Fe(`[OpenAI][${t}] Raw completion: ${JSON.stringify(i)}`);let a=i.choices[0].message;y(`[OpenAI][${t}] Response: finish_reason=${i.choices[0].finish_reason}`),y(`[OpenAI][${t}] Response has tool_calls: ${!!a.tool_calls}, count: ${a.tool_calls?.length||0}`),y(`[OpenAI][${t}] Response content: ${JSON.stringify(a.content)}`),a.content&&y(`[OpenAI][${t}] Response content preview: ${D(a.content,200)}`);let c=i.choices[0],p,m=c.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: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"}:e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format?Ka(e.response_format,"structured_output"):void 0,stream:!0},s=new Map;e.tools&&e.tools.length>0?(n.tools=e.tools.map(c=>{let p=this.sanitizeToolName(c.function.name);return s.set(p,c.function.name),{type:"function",function:{name:p,description:c.function.description,parameters:c.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),y(`[OpenAI][${t}] First tool: ${D(n.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice??"unset"}`),Z(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&&Fe(`[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 g=a.get(d);m.id&&(g.id=m.id),m.function?.name&&(g.name=m.function.name),m.function?.arguments&&(g.args+=m.function.arguments),Fe(`[OpenAI][${t}] tool_call_delta idx=${d} id=${m.id||g.id||""} name=${m.function?.name||g.name||""} args_delta=${D(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:c.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:c.usage}),p.finish_reason==="tool_calls"&&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||"{}")}));y(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(d=>d.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,o=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:o.data.map(n=>n.embedding),usage:o.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(s=>({id:s.id,type:"function",function:{name:this.sanitizeToolName(s.function.name),arguments:s.function.arguments}}))};if(typeof e.content=="string")return{role:e.role,content:e.content};if(e.content===null||e.content===void 0)return{role:e.role,content:""};let{normalizeImagePart:o}=await Promise.resolve().then(()=>(vt(),Gt)),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 Ha.APIError){let t=e.message;return e.status===401?new ge(t,e):e.status===429?new ie(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new I(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new I("Unknown error","UNKNOWN",500,e)}};l();var Ja="https://openrouter.ai/api/v1",Mn=class extends Ct{name="openrouter";_apiKey;constructor(e,t={}){super(e,Ja),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(`${Ja}/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"}};vt();l();l();var bn=class{tools=new Map;projects=new Map;config=ne;runtimeContext;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),o=new Set,n=[];for(let s of[...e,...t])o.has(s.name)||(o.add(s.name),n.push(s));return n}getSchemas(e){return(e?e.map(o=>this.tools.get(o)).filter(Boolean):this.getEnabled()).map(o=>({name:o.name,displayName:o.displayName,description:o.description,parameters:o.parameters,category:o.category,...o.cacheable!==void 0&&{cacheable:o.cacheable},...o.annotations!==void 0&&{annotations:o.annotations}}))}getByNames(e){return e.map(t=>this.tools.get(t)).filter(Boolean)}getByCategories(e){let t=new Set(e);return Array.from(this.tools.values()).filter(o=>t.has(o.category))}getCategories(){let e=new Set;for(let t of this.tools.values())e.add(t.category);return Array.from(e)}getAll(){return Array.from(this.tools.values())}setConfig(e){this.config=e}getConfig(){return this.config}get size(){return this.tools.size}async validateDependencies(e){let t=e.dependencies;if(!t||Object.keys(t).length===0)return[];let o=[];for(let n of Object.keys(t))try{await import(n)}catch{o.push(n)}return o}async loadProject(e){let t=await this.validateDependencies(e);if(t.length>0)throw new Error(`Tool project "${e.manifest.name}" has missing dependencies: ${t.join(", ")}. Install them with: npm install ${t.join(" ")}`);this.projects.set(e.manifest.name,e);for(let o of e.tools)this.register(o)}async loadProjects(e){for(let t of e)await this.loadProject(t)}getProject(e){return this.projects.get(e)}getProjects(){return Array.from(this.projects.values())}getProjectNames(){return Array.from(this.projects.keys())}async loadBuiltIn(){if(this.runtimeContext)return;let{ToolRuntimeContext:e}=await Promise.resolve().then(()=>(el(),Za));this.runtimeContext=new e;let{fsToolsProject:t}=await Promise.resolve().then(()=>(vs(),fp)),{execToolsProject:o}=await Promise.resolve().then(()=>(Ds(),pm)),{systemToolsProject:n}=await Promise.resolve().then(()=>(js(),zm)),{httpToolsProject:s}=await Promise.resolve().then(()=>(Bs(),Rd)),{githubToolsProject:i}=await Promise.resolve().then(()=>(ti(),Eu)),{webToolsProject:a}=await Promise.resolve().then(()=>(ui(),Xf)),{codingToolsProject:c}=await Promise.resolve().then(()=>(Di(),qh)),{gitToolsProject:p,createGitCloneTool:m}=await Promise.resolve().then(()=>(Ai(),wy)),{diffToolsProject:d}=await Promise.resolve().then(()=>(Ni(),Ny)),{dbToolsProject:g}=await Promise.resolve().then(()=>(Ii(),ab)),{cloudToolsProject:w}=await Promise.resolve().then(()=>(Li(),bb)),{slackToolsProject:b}=await Promise.resolve().then(()=>(Bi(),ow)),{k8sToolsProject:T}=await Promise.resolve().then(()=>(zi(),iw)),k={...p,tools:p.tools.map(v=>v.name==="git.clone"?m(this.runtimeContext.cloneState):v)};await this.loadProjects([t,o,n,s,i,a,c,k,d,g,w,b,T])}};l();import*as Ke from"fs";import*as $r from"path";S();var aw="toolpack.config.json";function lw(r){let e=cw(r);if(!Ke.existsSync(e))return{};try{let t=Ke.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function $C(r){let e=lw(r),t=DC(e.tools||e);return y(JSON.stringify(t??{})),t}function EC(r,e){let t=cw(e),o={};try{Ke.existsSync(t)&&(o=JSON.parse(Ke.readFileSync(t,"utf-8")))}catch{o={}}o.tools=r,Ke.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function DC(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??ne.enabled,autoExecute:r.autoExecute??ne.autoExecute,maxToolRounds:r.maxToolRounds??ne.maxToolRounds,toolChoicePolicy:r.toolChoicePolicy??ne.toolChoicePolicy,resultMaxChars:r.resultMaxChars??ne.resultMaxChars,enabledTools:r.enabledTools??ne.enabledTools,enabledToolCategories:r.enabledToolCategories??ne.enabledToolCategories,toolSearch:r.toolSearch??ne.toolSearch,additionalConfigurations:e}}function cw(r){return r?r.endsWith(".json")?$r.resolve(r):$r.resolve(r,aw):$r.resolve(process.cwd(),aw)}l();S();function MC(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&&O(`[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}}Wt();vs();Ds();js();Bs();ti();ui();Di();Ai();Ni();Ii();Li();zi();Bi();l();l();S();import{spawn as AC}from"child_process";import{EventEmitter as NC}from"events";var Er=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},Oe=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},wn=class extends NC{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 Oe("Client is shutting down");if(this.buffer="",this.process=AC(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new Oe("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=>{O(`[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 Oe(`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(`
473
+ `))!==-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 Oe("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 d=this.messageQueue.get(s);d&&(this.messageQueue.delete(s),d.reject(new Er(t,i)))},i)),this.messageQueue.set(s,{resolve:c,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
474
+ `)}catch(d){m&&clearTimeout(m),this.messageQueue.delete(s),p(d)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new Oe("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 Oe("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()}};S();var Dr=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 wn({...s,requestTimeoutMs:s.requestTimeoutMs??this.config.defaultTimeoutMs,autoReconnect:s.autoReconnect??this.config.autoReconnect??!0});this.setupClientEvents(i,t),await i.connect(),this.clients.set(t,i),this.serverConfigs.set(t,e),await this.discoverServerTools(t,i,e)}catch(i){throw me(`[MCP] Failed to connect to ${t}: ${i}`),i}}async connectAll(){let e=this.config.servers.filter(t=>t.autoConnect!==!1).map(t=>this.connectServer(t));await Promise.allSettled(e)}async disconnectServer(e){let t=this.clients.get(e);if(!t){O(`[MCP] Server ${e} not found`);return}P(`[MCP] Disconnecting from ${e}`);for(let[o,n]of this.toolOwners)n===e&&(this.toolDefinitions.delete(o),this.toolOwners.delete(o));await t.disconnect(),this.clients.delete(e),this.serverConfigs.delete(e)}async disconnectAll(){let e=Array.from(this.clients.keys()).map(t=>this.disconnectServer(t));await Promise.allSettled(e)}getToolDefinitions(){return Array.from(this.toolDefinitions.values())}getConnectedServers(){return Array.from(this.clients.keys())}isServerConnected(e){return this.clients.get(e)?.connected??!1}convertMcpTool(e,t,o,n){let s={type:"object",properties:e.inputSchema.properties||{},required:e.inputSchema.required||[]};return{name:`${o}${e.name}`,displayName:e.name,description:e.description||`MCP tool from ${t}`,category:"mcp",parameters:s,execute:async i=>{try{P(`[MCP] Executing ${e.name} on ${t}`);let a=await n.callTool(e.name,i);return JSON.stringify(a)}catch(a){throw me(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{me(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{O(`[MCP] ${t} closed with code ${o}`)}),e.on("reconnecting",({attempt:o,max:n})=>{P(`[MCP] ${t} reconnecting (${o}/${n})`)}),e.on("reconnected",({attempt:o})=>{P(`[MCP] ${t} reconnected after ${o} attempts`),this.refreshServerTools(t).catch(n=>{me(`[MCP] ${t} tool refresh failed after reconnect: ${n}`)})}),e.on("reconnect_failed",o=>{me(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{P(`[MCP] ${t} notification: ${JSON.stringify(o)}`)})}removeServerToolDefinitions(e){for(let[t,o]of this.toolOwners)o===e&&(this.toolDefinitions.delete(t),this.toolOwners.delete(t))}async discoverServerTools(e,t,o){let s=(await t.request("tools/list"))?.tools||[];P(`[MCP] Discovered ${s.length} tools from ${e}`),this.removeServerToolDefinitions(e);let i=o.toolPrefix||`mcp.${e}.`;for(let a of s){let 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 Hi(r){let e=new Dr(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 Ki(r){"mcpManager"in r&&await r.mcpManager.disconnectAll()}l();import*as Q from"fs/promises";import*as le from"path";function Vi(r){let e={},t=r.match(/^---\n([\s\S]*?)\n---/);if(!t||!t[1])return e;for(let o of t[1].split(`
475
+ `)){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 Qi(r){let e=r.match(/\[(.*)\]/);return!e||!e[1]?[]:e[1].split(",").map(t=>t.trim().replace(/"/g,"")).filter(Boolean)}function Ji(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(`
476
+ `).filter(n=>n.startsWith("- "))){let n=o.match(/^- "(.*)"/);n&&n[1]&&e.push(n[1])}return e}function pt(r,e){let t=r.match(new RegExp(`## ${e}\\n\\n([\\s\\S]*?)(?=\\n## |$)`));return t&&t[1]?t[1].trim():""}async function pw(r,e){async function t(o){let n;try{n=await Q.readdir(o)}catch{return null}for(let s of n){let i=le.join(o,s),a;try{a=await Q.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 OC(r){let e=[];async function t(o){let n;try{n=await Q.readdir(o)}catch{return}for(let s of n){let i=le.join(o,s),a;try{a=await Q.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function IC(r){let{name:e,title:t,description:o,triggers:n,instructions:s,examples:i,tags:a}=r,c=new Date().toISOString(),p=a&&a.length>0?a.map(d=>`"${d}"`).join(", "):"",m=["---",`name: ${e}`,`title: ${t}`,"version: 1.0.0",`updated: ${c}`,`tags: [${p}]`,"---","","## Description","",o,"","## Triggers","",n.map(d=>`- "${d}"`).join(`
477
477
  `),"","## Instructions","",s,""];return i&&m.push("## Examples","",i,""),m.join(`
478
- `)}function HC(r){return{name:"skill.create",displayName:"Create Skill",description:"Create a new .skill.md file in the skill library.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:'Skill name in kebab-case (e.g. "code-review"). Used as the filename.'},title:{type:"string",description:"Human-readable title for the skill (max 100 chars)."},description:{type:"string",description:"Short description for BM25 search indexing (max 300 chars)."},triggers:{type:"array",items:{type:"string"},description:"List of trigger phrases that activate this skill (min 1, max 10)."},instructions:{type:"string",description:"Behavioral instructions injected into context when the skill activates (max 2000 chars)."},examples:{type:"string",description:"Optional examples section (max 3000 chars, never auto-injected)."},tags:{type:"array",items:{type:"string"},description:"Optional tags for filtering and search (max 10)."},subfolder:{type:"string",description:'Optional subfolder within the skills directory (e.g. "coding").'}},required:["name","title","description","triggers","instructions"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers??[],i=e.instructions,a=e.examples,l=e.tags??[],p=e.subfolder;if(!/^[a-z][a-z0-9-]*$/.test(t))return JSON.stringify({error:"invalid_name",message:"Skill name must be kebab-case (lowercase letters, numbers, hyphens, starting with a letter)"},null,2);let m=p?ie.join(r,p):r;await Q.mkdir(m,{recursive:!0});let d=ie.join(m,`${t}.skill.md`);try{return await Q.access(d),JSON.stringify({error:"skill_exists",message:`Skill "${t}" already exists at ${d}. Use skill.update to modify it.`},null,2)}catch{}let g=zC({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:l});return await Q.writeFile(d,g,"utf-8"),JSON.stringify({success:!0,skill:t,path:d,message:`Skill "${o}" created successfully`},null,2)}}}function KC(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 bw(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 Q.readFile(n,"utf-8")).replace(/\r\n/g,`
479
- `),i=ta(s),a={name:i.name||t,title:i.title||t,version:i.version,tags:i.tags?oa(i.tags):[],updated:i.updated,path:n};return JSON.stringify(o==="metadata"?{skill:t,metadata:a}:o==="description"?{skill:t,description:pt(s,"Description")}:o==="triggers"?{skill:t,triggers:ea(s)}:o==="instructions"?{skill:t,instructions:pt(s,"Instructions")}:o==="examples"?{skill:t,examples:pt(s,"Examples")}:{skill:t,path:n,metadata:a,description:pt(s,"Description"),triggers:ea(s),instructions:pt(s,"Instructions"),examples:pt(s,"Examples")||void 0},null,2)}}}function JC(r){return{name:"skill.update",displayName:"Update Skill",description:"Update fields of an existing skill. Only provided fields are changed.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:"Skill name to update."},title:{type:"string",description:"New title (optional)."},description:{type:"string",description:"New description replacing the existing one (optional)."},triggers:{type:"array",items:{type:"string"},description:"New triggers list replacing the existing one (optional)."},instructions:{type:"string",description:"New instructions replacing the existing ones (optional)."},addExamples:{type:"string",description:"Additional examples text to append to the Examples section (optional)."},addTags:{type:"array",items:{type:"string"},description:"Tags to add to the existing tags (optional)."}},required:["name"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers,i=e.instructions,a=e.addExamples,l=e.addTags,p=await bw(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 Q.readFile(p,"utf-8")).replace(/\r\n/g,`
480
- `),d=ta(m),g=d.tags?oa(d.tags):[],b=d.title||t,w=d.version||"1.0.0",T=o??b,v=l?[...new Set([...g,...l])]:g,C=new Date().toISOString();if(n!==void 0&&(m=m.replace(/## Description\n\n[\s\S]*?(?=\n## )/,`## Description
478
+ `)}function LC(r){return{name:"skill.create",displayName:"Create Skill",description:"Create a new .skill.md file in the skill library.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:'Skill name in kebab-case (e.g. "code-review"). Used as the filename.'},title:{type:"string",description:"Human-readable title for the skill (max 100 chars)."},description:{type:"string",description:"Short description for BM25 search indexing (max 300 chars)."},triggers:{type:"array",items:{type:"string"},description:"List of trigger phrases that activate this skill (min 1, max 10)."},instructions:{type:"string",description:"Behavioral instructions injected into context when the skill activates (max 2000 chars)."},examples:{type:"string",description:"Optional examples section (max 3000 chars, never auto-injected)."},tags:{type:"array",items:{type:"string"},description:"Optional tags for filtering and search (max 10)."},subfolder:{type:"string",description:'Optional subfolder within the skills directory (e.g. "coding").'}},required:["name","title","description","triggers","instructions"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers??[],i=e.instructions,a=e.examples,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?le.join(r,p):r;await Q.mkdir(m,{recursive:!0});let d=le.join(m,`${t}.skill.md`);try{return await Q.access(d),JSON.stringify({error:"skill_exists",message:`Skill "${t}" already exists at ${d}. Use skill.update to modify it.`},null,2)}catch{}let g=IC({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:c});return await Q.writeFile(d,g,"utf-8"),JSON.stringify({success:!0,skill:t,path:d,message:`Skill "${o}" created successfully`},null,2)}}}function jC(r){return{name:"skill.read",displayName:"Read Skill",description:"Read a skill file by name. Optionally read only a specific section.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:"Skill name (without the .skill.md extension)."},section:{type:"string",enum:["all","metadata","description","triggers","instructions","examples"],description:"Which section to return (default: all).",default:"all"}},required:["name"]},async execute(e){let t=e.name,o=e.section||"all",n=await pw(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 Q.readFile(n,"utf-8")).replace(/\r\n/g,`
479
+ `),i=Vi(s),a={name:i.name||t,title:i.title||t,version:i.version,tags:i.tags?Qi(i.tags):[],updated:i.updated,path:n};return JSON.stringify(o==="metadata"?{skill:t,metadata:a}:o==="description"?{skill:t,description:pt(s,"Description")}:o==="triggers"?{skill:t,triggers:Ji(s)}:o==="instructions"?{skill:t,instructions:pt(s,"Instructions")}:o==="examples"?{skill:t,examples:pt(s,"Examples")}:{skill:t,path:n,metadata:a,description:pt(s,"Description"),triggers:Ji(s),instructions:pt(s,"Instructions"),examples:pt(s,"Examples")||void 0},null,2)}}}function FC(r){return{name:"skill.update",displayName:"Update Skill",description:"Update fields of an existing skill. Only provided fields are changed.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:"Skill name to update."},title:{type:"string",description:"New title (optional)."},description:{type:"string",description:"New description replacing the existing one (optional)."},triggers:{type:"array",items:{type:"string"},description:"New triggers list replacing the existing one (optional)."},instructions:{type:"string",description:"New instructions replacing the existing ones (optional)."},addExamples:{type:"string",description:"Additional examples text to append to the Examples section (optional)."},addTags:{type:"array",items:{type:"string"},description:"Tags to add to the existing tags (optional)."}},required:["name"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers,i=e.instructions,a=e.addExamples,c=e.addTags,p=await pw(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 Q.readFile(p,"utf-8")).replace(/\r\n/g,`
480
+ `),d=Vi(m),g=d.tags?Qi(d.tags):[],w=d.title||t,b=d.version||"1.0.0",T=o??w,k=c?[...new Set([...g,...c])]:g,v=new Date().toISOString();if(n!==void 0&&(m=m.replace(/## Description\n\n[\s\S]*?(?=\n## )/,`## Description
481
481
 
482
482
  ${n}
483
483
 
484
- `)),s!==void 0){let D=s.map(M=>`- "${M}"`).join(`
484
+ `)),s!==void 0){let C=s.map(_=>`- "${_}"`).join(`
485
485
  `);m=m.replace(/## Triggers\n\n[\s\S]*?(?=\n## )/,`## Triggers
486
486
 
487
- ${D}
487
+ ${C}
488
488
 
489
489
  `)}if(i!==void 0&&(m=m.replace(/## Instructions\n\n[\s\S]*?(?=\n## |$)/,`## Instructions
490
490
 
491
491
  ${i}
492
492
 
493
- `)),a){let D=m.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if(D){let M=D[1]??"",k=M.trim()?`
493
+ `)),a){let C=m.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if(C){let _=C[1]??"",E=_.trim()?`
494
494
 
495
495
  `:"";m=m.replace(/## Examples\n\n[\s\S]*?(?=\n## |$)/,`## Examples
496
496
 
497
- ${M}${k}${a}
497
+ ${_}${E}${a}
498
498
 
499
499
  `)}else m=m.trimEnd()+`
500
500
 
501
501
  ## Examples
502
502
 
503
503
  ${a}
504
- `}m=m.replace(/^---\n[\s\S]*?\n---/,["---",`name: ${t}`,`title: ${T}`,`version: ${w}`,`updated: ${C}`,`tags: [${v.map(D=>`"${D}"`).join(", ")}]`,"---"].join(`
505
- `)),await Q.writeFile(p,m,"utf-8");let x=[];return o&&x.push("title"),n!==void 0&&x.push("description"),s!==void 0&&x.push("triggers"),i!==void 0&&x.push("instructions"),a&&x.push("examples (appended)"),l&&x.push(`tags (+${l.length})`),JSON.stringify({success:!0,skill:t,path:p,updated:x,message:`Skill "${t}" updated successfully`},null,2)}}}function VC(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 Q.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 BC(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 Q.readFile(i,"utf-8")).replace(/\r\n/g,`
506
- `),l=ta(a),p=l.name||ie.basename(i,".skill.md"),m=l.title||p,d=l.tags?oa(l.tags):[];if(t&&!d.includes(t))continue;let g=ie.dirname(ie.relative(r,i)),b=g==="."?void 0:g.split(ie.sep)[0];o?s.push({name:p,title:m,tags:d,category:b,description:pt(a,"Description")||void 0,triggers:ea(a)}):s.push({name:p,title:m})}return JSON.stringify({skills:s,count:s.length,filtered:t?`by tag: ${t}`:null},null,2)}}}function QC(r){let e=ie.resolve(r?.dir??".toolpack/skills"),t=[HC(e),KC(e),JC(e),VC(e)];return{manifest:{key:"skill",name:"skill-tools",displayName:"Skill Management",version:"1.0.0",description:"Tools for creating, reading, updating, and listing agent skill files.",tools:["skill.create","skill.read","skill.update","skill.list"],category:"skills"},tools:t}}c();c();c();c();var na=`
504
+ `}m=m.replace(/^---\n[\s\S]*?\n---/,["---",`name: ${t}`,`title: ${T}`,`version: ${b}`,`updated: ${v}`,`tags: [${k.map(C=>`"${C}"`).join(", ")}]`,"---"].join(`
505
+ `)),await Q.writeFile(p,m,"utf-8");let x=[];return o&&x.push("title"),n!==void 0&&x.push("description"),s!==void 0&&x.push("triggers"),i!==void 0&&x.push("instructions"),a&&x.push("examples (appended)"),c&&x.push(`tags (+${c.length})`),JSON.stringify({success:!0,skill:t,path:p,updated:x,message:`Skill "${t}" updated successfully`},null,2)}}}function qC(r){return{name:"skill.list",displayName:"List Skills",description:"List all skills in the skill library, optionally filtered by tag.",category:"skills",parameters:{type:"object",properties:{tag:{type:"string",description:"Filter skills by tag (optional)."},verbose:{type:"boolean",description:"Include description and triggers in the output (default: false).",default:!1}},required:[]},async execute(e){let t=e.tag,o=e.verbose??!1;try{await Q.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 OC(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 Q.readFile(i,"utf-8")).replace(/\r\n/g,`
506
+ `),c=Vi(a),p=c.name||le.basename(i,".skill.md"),m=c.title||p,d=c.tags?Qi(c.tags):[];if(t&&!d.includes(t))continue;let g=le.dirname(le.relative(r,i)),w=g==="."?void 0:g.split(le.sep)[0];o?s.push({name:p,title:m,tags:d,category:w,description:pt(a,"Description")||void 0,triggers:Ji(a)}):s.push({name:p,title:m})}return JSON.stringify({skills:s,count:s.length,filtered:t?`by tag: ${t}`:null},null,2)}}}function WC(r){let e=le.resolve(r?.dir??".toolpack/skills"),t=[LC(e),jC(e),FC(e),qC(e)];return{manifest:{key:"skill",name:"skill-tools",displayName:"Skill Management",version:"1.0.0",description:"Tools for creating, reading, updating, and listing agent skill files.",tools:["skill.create","skill.read","skill.update","skill.list"],category:"skills"},tools:t}}l();l();l();l();var Xi=`
507
507
  You are a planning assistant. Given a user request, create a detailed step-by-step plan.
508
508
 
509
509
  Rules:
@@ -529,7 +529,7 @@ Rules:
529
529
  }
530
530
  ]
531
531
  }
532
- `,vG={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},ww={name:"Agent",planning:{enabled:!0,planningPrompt:na},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},XC=`
532
+ `,TG={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},mw={name:"Agent",planning:{enabled:!0,planningPrompt:Xi},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},UC=`
533
533
  Create a step-by-step plan for this coding task.
534
534
 
535
535
  Rules:
@@ -552,16 +552,16 @@ JSON Schema:
552
552
  }
553
553
  ]
554
554
  }
555
- `,Tw={name:"Coding",planning:{enabled:!0,planningPrompt:XC},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},xw={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var vw={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:ww,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},Cw={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:xw,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},kw={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:Tw,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"]}},Fr=[vw,kw,Cw],Ot="chat";var kn=class{modes=new Map;orderedNames=[];constructor(){for(let e of Fr)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(Ot);if(!e)throw new Error(`Default mode "${Ot}" not found in registry`);return e}getNext(e){let t=this.orderedNames.indexOf(e),o=t===-1?0:(t+1)%this.orderedNames.length,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(Fr.some(n=>n.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(n=>n!==e)),o}};c();function YC(r){return{name:r.name,displayName:r.displayName,description:r.description||r.displayName,systemPrompt:r.systemPrompt,allowedToolCategories:r.allowedToolCategories||[],blockedToolCategories:r.blockedToolCategories||[],allowedTools:r.allowedTools||[],blockedTools:r.blockedTools||[],blockAllTools:r.blockAllTools||!1,response_format:r.response_format,baseContext:r.baseContext,workflow:r.workflow,skillInterceptor:r.skillInterceptor??!1,rulesDir:r.rulesDir,streaming:r.streaming}}c();var ra={planning:{enabled:!1},progress:{enabled:!0}};c();S();var ZC=na,Sn=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||ZC,n=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);y(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${n}..."`);let s=e.messages.filter(p=>p.role==="system"),i=e.messages.filter(p=>p.role!=="system"),a=[{role:"system",content:o},...s,...i],l={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:a};try{let p=await this.client.generate(l,t),m=this.parsePlan(p.content||"",e,p);return P(`[Planner] createPlan() succeeded plan.id=${m.id} steps=${m.steps.length}`),m}catch(p){return L(`[Planner] createPlan() failed, using fallback: ${p.message}`),this.createFallbackPlan(e)}}parsePlan(e,t,o){try{let n=JSON.parse(e);if(!n.summary||!Array.isArray(n.steps))throw new Error("Invalid plan structure: missing summary or steps array");let s=this.config?.maxSteps??20,i=n.steps.slice(0,s);n.steps.length>s&&L(`[Planner] parsePlan() truncated ${n.steps.length} steps to maxSteps=${s}`),y(`[Planner] parsePlan() parsed ${i.length} steps successfully`);let a=i.map((p,m)=>({id:`step-${Date.now()}-${m}`,number:p.number||m+1,description:p.description||"Unknown step",expectedTools:p.expectedTools||[],dependsOn:p.dependsOn||[],status:"pending"})),l=t.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}`,request:l,summary:n.summary,steps:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(n){return L(`[Planner] parsePlan() failed: ${n.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){L("[Planner] createFallbackPlan() \u2014 creating single-step fallback due to plan generation failure");let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}-fallback`,request:t,summary:"Fallback single-step plan due to generation failure",steps:[{id:"step-1",number:1,description:"Execute the user request",status:"pending",expectedTools:[],dependsOn:[]}],status:"draft",createdAt:new Date}}};c();import{EventEmitter as ek}from"events";S();var qr=class extends ek{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new wt,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=et(e.messages);if(!o)return!1;let n=this.queryClassifier.classify(o),s=this.config.complexityRouting.confidenceThreshold??.6,i=!1;switch(n.type){case"action":i=!1;break;case"conversational":i=!0;break;case"analytical":i=n.confidence>=s;break}return y(`[Workflow] shouldRouteSimpleQuery() type=${n.type} confidence=${n.confidence.toFixed(2)} threshold=${s} shouldRoute=${i} strategy=${t}`),i}async execute(e,t){if(this.shouldRouteSimpleQuery(e))return this.executeDirect(e,t);let o=this.config.planning?.enabled;if(y(`[Workflow] execute() planningEnabled=${o} provider=${t??"default"}`),!o)return y("[Workflow] execute() mode=direct"),this.executeDirect(e,t);y("[Workflow] execute() mode=plan-direct \u2014 creating plan");let n=await this.createPlan(e,t);if(this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){P(`[Workflow] Plan "${n.id}" requires approval \u2014 waiting`),this.emitProgress(n,"awaiting_approval","Waiting for plan approval");let s=await this.waitForApproval(n.id);if(this.emit("workflow:plan_decision",n,s),!s)return P(`[Workflow] Plan "${n.id}" rejected by user`),n.status="cancelled",this.emitProgress(n,"failed","Plan rejected by user"),{success:!1,plan:n,error:"Plan rejected by user",metrics:{totalDuration:0,stepsCompleted:0,stepsFailed:0,retriesUsed:0}};P(`[Workflow] Plan "${n.id}" approved`)}return n.status="approved",this.executePlanDirect(n,e,t)}async executeDirect(e,t){let o=Date.now(),n=this.createDummyPlan(e);y(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(n,"executing","Direct execution");let s=await this.client.generate(e,t);n.status="completed",n.completedAt=new Date,n.steps[0].status="completed";let i=Date.now()-o;y(`[Workflow] executeDirect() completed in ${i}ms content_len=${s.content?.length??0}`);let a={success:!0,plan:n,output:s.content||void 0,response:s,metrics:{totalDuration:Date.now()-o,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",n,a),this.emitProgress(n,"completed","Done"),a}catch(s){n.status="failed",n.completedAt=new Date,n.steps[0].status="failed",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){y(`[Workflow] createPlan() provider=${t??"default"}`);let o=this.createDummyPlan(e);o.status="draft",this.emitProgress(o,"planning","Creating plan...");let n=await this.planner.createPlan(e,t);return P(`[Workflow] createPlan() completed plan.id=${n.id} steps=${n.steps.length}`),n}async executePlanDirect(e,t,o){let n=Date.now();e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),this.emitProgress(e,"executing","Executing plan",10),y(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
555
+ `,dw={name:"Coding",planning:{enabled:!0,planningPrompt:UC},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},uw={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var fw={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:mw,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},gw={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:uw,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},hw={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:dw,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"]}},Mr=[fw,hw,gw],At="chat";var Tn=class{modes=new Map;orderedNames=[];constructor(){for(let e of Mr)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(At);if(!e)throw new Error(`Default mode "${At}" 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(Mr.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 GC(r){return{name:r.name,displayName:r.displayName,description:r.description||r.displayName,systemPrompt:r.systemPrompt,allowedToolCategories:r.allowedToolCategories||[],blockedToolCategories:r.blockedToolCategories||[],allowedTools:r.allowedTools||[],blockedTools:r.blockedTools||[],blockAllTools:r.blockAllTools||!1,response_format:r.response_format,baseContext:r.baseContext,workflow:r.workflow,skillInterceptor:r.skillInterceptor??!1,rulesDir:r.rulesDir,streaming:r.streaming}}l();var Yi={planning:{enabled:!1},progress:{enabled:!0}};l();S();var BC=Xi,xn=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||BC,n=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);y(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${n}..."`);let s=e.messages.filter(p=>p.role==="system"),i=e.messages.filter(p=>p.role!=="system"),a=[{role:"system",content:o},...s,...i],c={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:a};try{let p=await this.client.generate(c,t),m=this.parsePlan(p.content||"",e,p);return P(`[Planner] createPlan() succeeded plan.id=${m.id} steps=${m.steps.length}`),m}catch(p){return O(`[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&&O(`[Planner] parsePlan() truncated ${n.steps.length} steps to maxSteps=${s}`),y(`[Planner] parsePlan() parsed ${i.length} steps successfully`);let a=i.map((p,m)=>({id:`step-${Date.now()}-${m}`,number:p.number||m+1,description:p.description||"Unknown step",expectedTools:p.expectedTools||[],dependsOn:p.dependsOn||[],status:"pending"})),c=t.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}`,request:c,summary:n.summary,steps:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(n){return O(`[Planner] parsePlan() failed: ${n.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){O("[Planner] createFallbackPlan() \u2014 creating single-step fallback due to plan generation failure");let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}-fallback`,request:t,summary:"Fallback single-step plan due to generation failure",steps:[{id:"step-1",number:1,description:"Execute the user request",status:"pending",expectedTools:[],dependsOn:[]}],status:"draft",createdAt:new Date}}};l();import{EventEmitter as zC}from"events";S();var Ar=class extends zC{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new wt,this.planner=new xn(e,t.planning)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new xn(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=Ze(e.messages);if(!o)return!1;let n=this.queryClassifier.classify(o),s=this.config.complexityRouting.confidenceThreshold??.6,i=!1;switch(n.type){case"action":i=!1;break;case"conversational":i=!0;break;case"analytical":i=n.confidence>=s;break}return y(`[Workflow] shouldRouteSimpleQuery() type=${n.type} confidence=${n.confidence.toFixed(2)} threshold=${s} shouldRoute=${i} strategy=${t}`),i}async execute(e,t){if(this.shouldRouteSimpleQuery(e))return this.executeDirect(e,t);let o=this.config.planning?.enabled;if(y(`[Workflow] execute() planningEnabled=${o} provider=${t??"default"}`),!o)return y("[Workflow] execute() mode=direct"),this.executeDirect(e,t);y("[Workflow] execute() mode=plan-direct \u2014 creating plan");let n=await this.createPlan(e,t);if(this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){P(`[Workflow] Plan "${n.id}" requires approval \u2014 waiting`),this.emitProgress(n,"awaiting_approval","Waiting for plan approval");let s=await this.waitForApproval(n.id);if(this.emit("workflow:plan_decision",n,s),!s)return P(`[Workflow] Plan "${n.id}" rejected by user`),n.status="cancelled",this.emitProgress(n,"failed","Plan rejected by user"),{success:!1,plan:n,error:"Plan rejected by user",metrics:{totalDuration:0,stepsCompleted:0,stepsFailed:0,retriesUsed:0}};P(`[Workflow] Plan "${n.id}" approved`)}return n.status="approved",this.executePlanDirect(n,e,t)}async executeDirect(e,t){let o=Date.now(),n=this.createDummyPlan(e);y(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(n,"executing","Direct execution");let s=await this.client.generate(e,t);n.status="completed",n.completedAt=new Date,n.steps[0].status="completed";let i=Date.now()-o;y(`[Workflow] executeDirect() completed in ${i}ms content_len=${s.content?.length??0}`);let a={success:!0,plan:n,output:s.content||void 0,response:s,metrics:{totalDuration:Date.now()-o,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",n,a),this.emitProgress(n,"completed","Done"),a}catch(s){n.status="failed",n.completedAt=new Date,n.steps[0].status="failed",O(`[Workflow] executeDirect() failed: ${s.message}`);let i={success:!1,plan:n,error:s.message,metrics:{totalDuration:Date.now()-o,stepsCompleted:0,stepsFailed:1,retriesUsed:0}};return this.emit("workflow:failed",n,s),this.emitProgress(n,"failed","Execution failed"),i}}async createPlan(e,t){y(`[Workflow] createPlan() provider=${t??"default"}`);let o=this.createDummyPlan(e);o.status="draft",this.emitProgress(o,"planning","Creating plan...");let n=await this.planner.createPlan(e,t);return P(`[Workflow] createPlan() completed plan.id=${n.id} steps=${n.steps.length}`),n}async executePlanDirect(e,t,o){let n=Date.now();e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),this.emitProgress(e,"executing","Executing plan",10),y(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
556
556
  You have created the following plan to fulfill the request:
557
557
  Summary: ${e.summary}
558
558
 
559
559
  Steps:
560
- ${e.steps.map(l=>`${l.number}. ${l.description}`).join(`
560
+ ${e.steps.map(c=>`${c.number}. ${c.description}`).join(`
561
561
  `)}
562
562
 
563
563
  Execute this plan now.
564
- `.trim(),i=this.injectPlanContext(t.messages,s),a={...t,messages:i};try{let l=await this.client.generate(a,o);e.steps.forEach(m=>{m.status="completed",m.result={success:!0,output:l.content||"",response:l}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,n,0),y(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-n}ms`);let p={success:!0,plan:e,output:l.content||void 0,response:l,metrics:e.metrics};return this.emit("workflow:completed",e,p),this.emitProgress(e,"completed","Done"),p}catch(l){e.status="failed",e.completedAt=new Date,L(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${l.message}`);let p={success:!1,plan:e,error:l.message,metrics:this.computeMetrics(e,n,0)};return this.emit("workflow:failed",e,l),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),l={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",l)}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(`
564
+ `.trim(),i=this.injectPlanContext(t.messages,s),a={...t,messages:i};try{let c=await this.client.generate(a,o);e.steps.forEach(m=>{m.status="completed",m.result={success:!0,output:c.content||"",response:c}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,n,0),y(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-n}ms`);let p={success:!0,plan:e,output:c.content||void 0,response:c,metrics:e.metrics};return this.emit("workflow:completed",e,p),this.emitProgress(e,"completed","Done"),p}catch(c){e.status="failed",e.completedAt=new Date,O(`[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(`
565
565
  `);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}
566
566
 
567
567
  ---
@@ -586,8 +586,8 @@ ${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
586
586
  `)}
587
587
 
588
588
  Execute this plan now.
589
- `.trim(),s={...t,messages:this.injectPlanContext(t.messages,n)},i="";for await(let a of this.client.stream(s,o))a.delta&&(i+=a.delta),yield a;e.steps.forEach(a=>{a.status="completed",a.result={success:!0,output:i}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:i,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)}),this.emitProgress(e,"completed","Done")}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};c();import{EventEmitter as Mw}from"events";S();var Aw=class r extends Mw{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 qr(this.client,ra,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}buildKnowledgeRequestTools(){return this.knowledgeLayers.length===0?[]:this.knowledgeLayers.length===1?[this.knowledgeLayers[0].toTool(),{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async s=>({success:!0,id:await this.knowledgeLayers[0].add(s.content,s.metadata),message:"Content added to knowledge base successfully."})}]:[{name:"knowledge_search",displayName:"Knowledge Search",description:`Search across ${this.knowledgeLayers.length} knowledge layers for relevant information.`,category:"search",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Search query to find relevant information"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"},threshold:{type:"number",description:"Minimum similarity threshold 0-1 (default: 0.7)"},filter:{type:"object",description:"Optional metadata filters"}},required:["query"]},execute:async o=>{let s=(await Promise.all(this.knowledgeLayers.map(async(a,l)=>(await a.toTool().execute({query:o.query,limit:o.limit,threshold:o.threshold,filter:o.filter})).map(d=>({...d,_layer:l}))))).flat();s.sort((a,l)=>(l.score??0)-(a.score??0));let i=o.limit??10;return s.slice(0,i)}},{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the primary knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async o=>({success:!0,id:await this.knowledgeLayers[0].add(o.content,o.metadata),message:"Content added to knowledge base successfully."})}]}prepareRequest(e){let t=[...this.buildKnowledgeRequestTools(),...e.requestTools||[]];if(t.length===0)return e;let o=new Map;for(let n of t)o.set(n.name,n);return{...e,requestTools:Array.from(o.values())}}static async init(e){let t=Gn(e.configPath);Na(t.logging);let o=new vn,n=Ho(e.configPath);o.setConfig(n),e.tools&&await o.loadBuiltIn(),e.customTools&&await o.loadProjects(e.customTools);let s=null,i=e.mcp||t.mcp;if(i)try{P("[MCP] Initializing MCP tool integration");let $=await Yi(i);s=$,await o.loadProjects([$]),P(`[MCP] Loaded ${$.tools.length} tools from MCP servers`)}catch($){pe(`[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,g=e.defaultProvider||e.provider;if(e.providers)for(let[$,E]of Object.entries(e.providers)){let R=$===g,N=await r.createProvider($,E,e.configPath,!R);N&&(m[$]=N)}else if(e.provider){let $={apiKey:e.apiKey,model:e.model,projectId:e.projectId,location:e.location,googleAuthOptions:e.googleAuthOptions,thinkingBudget:e.thinkingBudget,region:e.region},E=await r.createProvider(e.provider,$,e.configPath,!1);E&&(m[e.provider]=E)}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,R])=>(R.name=R.name||E,R));for(let E of $){if(typeof E.generate!="function"||typeof E.stream!="function"||typeof E.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let R=E.name;if(!R)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(m[R])throw new Error(`Custom provider name "${R}" conflicts with a built-in provider designation. Choose a different name.`);d.add(R),m[R]=E}}if(!g&&e.customProviders&&(g=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!g)throw new Error("No default provider specified.");let b=new kn;if(e.customModes)for(let $ of e.customModes)b.register($);let w={...p,...e.modeOverrides||{}};for(let[$,E]of Object.entries(w)){let R=b.get($);if(R){E.systemPrompt!==void 0&&(R.systemPrompt=E.systemPrompt),E.toolSearch&&(R.toolSearch={...R.toolSearch||{},...E.toolSearch});for(let[N,ue]of Object.entries(E))N!=="systemPrompt"&&N!=="toolSearch"&&(R[N]=ue)}}let T=t.hitl||{};e.confirmationMode!==void 0&&(T.confirmationMode=e.confirmationMode),T.enabled===void 0&&e.onToolConfirm&&(T.enabled=!0),T.confirmationMode===void 0&&e.onToolConfirm&&(T.confirmationMode="all");let v=new $n({providers:m,defaultProvider:g,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:a,disableBaseContext:l,hitlConfig:Object.keys(T).length>0?T:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow}),C=new r(v,g,b),x=e.knowledge,D=x==null?[]:Array.isArray(x)?x:[x];C.knowledgeLayers=D.filter($=>!!$&&typeof $.toTool=="function"),C.customProviderNames=d,C.mcpToolProject=s,C._interceptors=e.interceptors??[];for(let $ of C._interceptors)$.init&&await $.init();let M=e.defaultMode||Ot,k=b.get(M);return k&&(v.setMode(k),k.workflow&&C.workflowExecutor.setConfig(k.workflow)),C}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new Mn({projectId:t.projectId,location:t.location,googleAuthOptions:t.googleAuthOptions,thinkingBudget:t.thinkingBudget});if(e==="anthropic-vertex")return new Dn({projectId:t.projectId,region:t.region});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 Ct(i,t.baseUrl);case"anthropic":return new En(i,t.baseUrl);case"gemini":return new An(i);case"openrouter":return new In(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new Xt({baseUrl:t.baseUrl||On(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||On(o);return new nt({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),o=this.resolveRequestModeName(o),(o.mode!==void 0?o.mode:this.getMode())?.workflow?.planning?.enabled){let s=await this.workflowExecutor.execute(o,t||this.activeProviderName),i=0,a=0,l=0,p={steps:[]};s.plan.planningResponse?.usage&&(i+=s.plan.planningResponse.usage.prompt_tokens,a+=s.plan.planningResponse.usage.completion_tokens||0,l+=s.plan.planningResponse.usage.total_tokens,p.planning=s.plan.planningResponse.usage);for(let d of s.plan.steps)if(d.status==="completed"&&d.result?.response?.usage){let g=d.result.response.usage;i+=g.prompt_tokens,a+=g.completion_tokens||0,l+=g.total_tokens,p.steps.push({stepNumber:d.number,description:d.description,usage:g})}let m={prompt_tokens:i,completion_tokens:a,total_tokens:l};return s.response?{...s.response,content:s.output||s.response.content||null,usage:m,usage_details:p}:{content:s.output||null,usage:m,usage_details:p}}return this._interceptors.length>0?this._buildInterceptorChain(this._interceptors,i=>this.client.generate(i??o,t))(o):this.client.generate(o,t)}resolveRequestModeName(e){if(typeof e.mode!="string")return e;let t=this.modeRegistry.get(e.mode);if(!t)throw new Error(`Mode "${e.mode}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return{...e,mode: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);o=this.resolveRequestModeName(o);let n=o.mode!==void 0?o.mode: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||ot();if(t)try{let o=Qt(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 Zi(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[o,n]of e.entries()){let s=this.customProviderNames.has(o),i=[];try{i=await n.getModels()}catch(a){L(`[Toolpack] Failed to fetch models for provider '${o}': ${a}`)}t.push({name:o,displayName:n.getDisplayName(),type:s?"custom":"built-in",models:i})}return t}async loadToolProject(e){let t=this.client.getToolRegistry();if(t)await t.loadProject(e);else throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.")}async startMcpServer(e){let t=this.client.getToolRegistry();if(!t)throw new Error("No tool registry configured. Initialize Toolpack with tools enabled: Toolpack.init({ tools: true })");let o;try{o=(await Promise.resolve().then(()=>(Dw(),Ew))).startMcpServer}catch(s){throw s instanceof Error&&s.code==="MODULE_NOT_FOUND"&&s.message.includes("@modelcontextprotocol")?new Error(`MCP server requires @modelcontextprotocol/sdk. Install it with:
590
- npm install @modelcontextprotocol/sdk`):s}let n=e.searchMode?s=>this.client.executeToolSearch(s):void 0;return o(t,e,n)}async listModels(){let e=await this.listProviders(),t=[];for(let o of e)for(let n of o.models)t.push({...n,provider:o.name});return t}setMode(e){let t=this.modeRegistry.get(e);if(!t)throw new Error(`Mode "${e}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return this.client.setMode(t),t.workflow?this.workflowExecutor.setConfig(t.workflow):this.workflowExecutor.setConfig(ra),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 Mw&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,o)=>this.emit("workflow:completed",t,o)),e.on("workflow:failed",(t,o)=>this.emit("workflow:failed",t,o))}};c();c();c();var Wr=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 la=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new Wr(e.maxConversations??500),this.maxMessagesPerConversation=e.maxMessagesPerConversation??500}async append(e){let t=this.lru.get(e.conversationId);t||(t=[],this.lru.set(e.conversationId,t)),!t.some(o=>o.id===e.id)&&(t.push(e),t.sort((o,n)=>o.timestamp.localeCompare(n.timestamp)),t.length>this.maxMessagesPerConversation&&t.splice(0,t.length-this.maxMessagesPerConversation))}async get(e,t={}){let n=(this.lru.get(e)??[]).slice();if(t.scope!==void 0&&(n=n.filter(s=>s.scope===t.scope)),t.sinceTimestamp!==void 0&&(n=n.filter(s=>s.timestamp>=t.sinceTimestamp)),t.participantIds!==void 0&&t.participantIds.length>0){let s=new Set(t.participantIds);n=n.filter(i=>s.has(i.participant.id))}return t.limit!==void 0&&n.length>t.limit&&(n=n.slice(n.length-t.limit)),n}async search(e,t,o={}){let n=this.lru.get(e)??[],s=t.toLowerCase(),i=o.limit??10,a=o.tokenCap??2e3,l=n.filter(d=>d.content.toLowerCase().includes(s)).slice().reverse(),p=[],m=0;for(let d of l){if(p.length>=i)break;let g=Math.ceil(d.content.length/4);if(p.length>0&&m+g>a)break;p.push(d),m+=g}return p}async deleteMessages(e,t){let o=this.lru.get(e);if(!o||t.length===0)return;let n=new Set(t),s=o.filter(i=>!n.has(i.id));this.lru.set(e,s)}clearConversation(e){this.lru.set(e,[])}get conversationCount(){return this.lru.size}};c();import fk from"better-sqlite3";import*as It from"fs";import*as Pn from"path";function gk(){let r=Pn.join(process.cwd(),".toolpack","db","conversation");return It.existsSync(r)||It.mkdirSync(r,{recursive:!0}),Pn.join(r,"conversation.sqlite")}var ca=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??gk(),o=Pn.dirname(t);if(It.existsSync(o)||It.mkdirSync(o,{recursive:!0}),this.db=new fk(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(`
589
+ `.trim(),s={...t,messages:this.injectPlanContext(t.messages,n)},i="";for await(let a of this.client.stream(s,o))a.delta&&(i+=a.delta),yield a;e.steps.forEach(a=>{a.status="completed",a.result={success:!0,output:i}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:i,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)}),this.emitProgress(e,"completed","Done")}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};l();import{EventEmitter as kw}from"events";S();var Sw=class r extends kw{client;activeProviderName;modeRegistry;workflowExecutor;knowledgeLayers=[];customProviderNames=new Set;mcpToolProject=null;_interceptors=[];constructor(e,t,o){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=o;let n=this.client.getProvider(t);n&&this.forwardEvents(n),this.workflowExecutor=new Ar(this.client,Yi,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(d=>({...d,_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){Ra(e.logging);let t=new bn,o={...ne,...e.toolsConfig||{}};t.setConfig(o),e.tools&&await t.loadBuiltIn();let n=null,s=e.mcp;if(s)try{P("[MCP] Initializing MCP tool integration");let x=await Hi(s);n=x,await t.loadProjects([x]),P(`[MCP] Loaded ${x.tools.length} tools from MCP servers`)}catch(x){me(`[MCP] Failed to initialize MCP tools: ${x}`)}let i=e.disableBaseContext??!1,a={},c=new Set,p=e.defaultProvider||e.provider;if(e.providers)for(let[x,C]of Object.entries(e.providers)){let _=x===p,E=await r.createProvider(x,C,void 0,!_);E&&(a[x]=E)}else if(e.provider){let x={apiKey:e.apiKey,model:e.model,projectId:e.projectId,location:e.location,googleAuthOptions:e.googleAuthOptions,thinkingBudget:e.thinkingBudget,region:e.region},C=await r.createProvider(e.provider,x,void 0,!1);C&&(a[e.provider]=C)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let x=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([C,_])=>(_.name=_.name||C,_));for(let C of x){if(typeof C.generate!="function"||typeof C.stream!="function"||typeof C.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 _=C.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(a[_])throw new Error(`Custom provider name "${_}" conflicts with a built-in provider designation. Choose a different name.`);c.add(_),a[_]=C}}if(!p&&e.customProviders&&(p=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!p)throw new Error("No default provider specified.");let m=new Tn;if(e.customModes)for(let x of e.customModes)m.register(x);let d={...e.hitl||{}};e.confirmationMode!==void 0&&(d.confirmationMode=e.confirmationMode),d.enabled===void 0&&e.onToolConfirm&&(d.enabled=!0),d.confirmationMode===void 0&&e.onToolConfirm&&(d.confirmationMode="all");let g=new Sn({providers:a,defaultProvider:p,toolRegistry:t,toolsConfig:t.getConfig(),disableBaseContext:i,hitlConfig:Object.keys(d).length>0?d:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow}),w=new r(g,p,m),b=e.knowledge,T=b==null?[]:Array.isArray(b)?b:[b];w.knowledgeLayers=T.filter(x=>!!x&&typeof x.toTool=="function"),w.customProviderNames=c,w.mcpToolProject=n,w._interceptors=e.interceptors??[];for(let x of w._interceptors)x.init&&await x.init();let k=e.defaultMode||At,v=m.get(k);return v&&(g.setMode(v),v.workflow&&w.workflowExecutor.setConfig(v.workflow)),w}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new Rn({projectId:t.projectId,location:t.location,googleAuthOptions:t.googleAuthOptions,thinkingBudget:t.thinkingBudget});if(e==="anthropic-vertex")return new _n({projectId:t.projectId,region:t.region});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 Ct(i,t.baseUrl);case"anthropic":return new Pn(i,t.baseUrl);case"gemini":return new $n(i);case"openrouter":return new Mn(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new zt({baseUrl:t.baseUrl||Dn(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||Dn(o);return new ot({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),o=this.resolveRequestModeName(o),(o.mode!==void 0?o.mode: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 d of s.plan.steps)if(d.status==="completed"&&d.result?.response?.usage){let g=d.result.response.usage;i+=g.prompt_tokens,a+=g.completion_tokens||0,c+=g.total_tokens,p.steps.push({stepNumber:d.number,description:d.description,usage:g})}let m={prompt_tokens:i,completion_tokens:a,total_tokens:c};return s.response?{...s.response,content:s.output||s.response.content||null,usage:m,usage_details:p}:{content:s.output||null,usage:m,usage_details:p}}return this._interceptors.length>0?this._buildInterceptorChain(this._interceptors,i=>this.client.generate(i??o,t))(o):this.client.generate(o,t)}resolveRequestModeName(e){if(typeof e.mode!="string")return e;let t=this.modeRegistry.get(e.mode);if(!t)throw new Error(`Mode "${e.mode}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return{...e,mode: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);o=this.resolveRequestModeName(o);let n=o.mode!==void 0?o.mode: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||tt();if(t)try{let o=Bt(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){O(`[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 Ki(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){O(`[Toolpack] Failed to fetch models for provider '${o}': ${a}`)}t.push({name:o,displayName:n.getDisplayName(),type:s?"custom":"built-in",models:i})}return t}async loadToolProject(e){let t=this.client.getToolRegistry();if(t)await t.loadProject(e);else throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.")}async startMcpServer(e){let t=this.client.getToolRegistry();if(!t)throw new Error("No tool registry configured. Initialize Toolpack with tools enabled: Toolpack.init({ tools: true })");let o;try{o=(await Promise.resolve().then(()=>(Cw(),vw))).startMcpServer}catch(s){throw s instanceof Error&&s.code==="MODULE_NOT_FOUND"&&s.message.includes("@modelcontextprotocol")?new Error(`MCP server requires @modelcontextprotocol/sdk. Install it with:
590
+ npm install @modelcontextprotocol/sdk`):s}let n=e.searchMode?s=>this.client.executeToolSearch(s):void 0;return o(t,e,n)}async listModels(){let e=await this.listProviders(),t=[];for(let o of e)for(let n of o.models)t.push({...n,provider:o.name});return t}setMode(e){let t=this.modeRegistry.get(e);if(!t)throw new Error(`Mode "${e}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return this.client.setMode(t),t.workflow?this.workflowExecutor.setConfig(t.workflow):this.workflowExecutor.setConfig(Yi),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 kw&&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 Nr=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 oa=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new Nr(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(d=>d.content.toLowerCase().includes(s)).slice().reverse(),p=[],m=0;for(let d of c){if(p.length>=i)break;let g=Math.ceil(d.content.length/4);if(p.length>0&&m+g>a)break;p.push(d),m+=g}return p}async deleteMessages(e,t){let o=this.lru.get(e);if(!o||t.length===0)return;let n=new Set(t),s=o.filter(i=>!n.has(i.id));this.lru.set(e,s)}clearConversation(e){this.lru.set(e,[])}get conversationCount(){return this.lru.size}};l();import sk from"better-sqlite3";import*as Nt from"fs";import*as vn from"path";function ik(){let r=vn.join(process.cwd(),".toolpack","db","conversation");return Nt.existsSync(r)||Nt.mkdirSync(r,{recursive:!0}),vn.join(r,"conversation.sqlite")}var na=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??ik(),o=vn.dirname(t);if(Nt.existsSync(o)||Nt.mkdirSync(o,{recursive:!0}),this.db=new sk(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(`
591
591
  CREATE TABLE IF NOT EXISTS messages (
592
592
  id TEXT NOT NULL,
593
593
  conversation_id TEXT NOT NULL,
@@ -602,7 +602,7 @@ Execute this plan now.
602
602
  )`),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 (
603
603
  id, conversation_id, participant_kind, participant_id, participant_display_name,
604
604
  content, timestamp, scope, metadata
605
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),o=e.metadata?JSON.stringify(e.metadata):null,n=t.run(e.id,e.conversationId,e.participant.kind,e.participant.id,e.participant.displayName??null,e.content,e.timestamp,e.scope,o);if(this.useFTS&&n.changes>0){let s=`${e.conversationId}:${e.id}`;this.db.prepare("INSERT INTO messages_fts (doc_key, content) VALUES (?, ?)").run(s,e.content)}if(this.maxMessagesPerConversation>0){let a=this.db.prepare("SELECT COUNT(1) as c FROM messages WHERE conversation_id = ?").get(e.conversationId)?.c??0;if(a>this.maxMessagesPerConversation){let l=a-this.maxMessagesPerConversation,m=this.db.prepare("SELECT id FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC LIMIT ?").all(e.conversationId,l).map(d=>d.id);if(m.length>0){let d=m.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${d})`).run(e.conversationId,...m),this.useFTS){let b=m.map(v=>`${e.conversationId}:${v}`),w=b.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${w})`).run(...b)}}}}}async get(e,t={}){let o=["conversation_id = ?"],n=[e];if(t.scope!==void 0&&(o.push("scope = ?"),n.push(t.scope)),t.sinceTimestamp!==void 0&&(o.push("timestamp >= ?"),n.push(t.sinceTimestamp)),t.participantIds&&t.participantIds.length>0){let p=t.participantIds.map(()=>"?").join(",");o.push(`participant_id IN (${p})`),n.push(...t.participantIds)}let i=`SELECT id, conversation_id, participant_kind, participant_id, participant_display_name, content, timestamp, scope, metadata FROM messages ${o.length?`WHERE ${o.join(" AND ")}`:""} ORDER BY timestamp ASC`,l=this.db.prepare(i).all(n).map(p=>this.rowToMessage(p));return t.limit!==void 0&&l.length>t.limit&&(l=l.slice(l.length-t.limit)),l}async search(e,t,o={}){let n=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
605
+ ) 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(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 w=m.map(k=>`${e.conversationId}:${k}`),b=w.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${b})`).run(...w)}}}}}async get(e,t={}){let o=["conversation_id = ?"],n=[e];if(t.scope!==void 0&&(o.push("scope = ?"),n.push(t.scope)),t.sinceTimestamp!==void 0&&(o.push("timestamp >= ?"),n.push(t.sinceTimestamp)),t.participantIds&&t.participantIds.length>0){let p=t.participantIds.map(()=>"?").join(",");o.push(`participant_id IN (${p})`),n.push(...t.participantIds)}let i=`SELECT id, conversation_id, participant_kind, participant_id, participant_display_name, content, timestamp, scope, metadata FROM messages ${o.length?`WHERE ${o.join(" AND ")}`:""} ORDER BY timestamp ASC`,c=this.db.prepare(i).all(n).map(p=>this.rowToMessage(p));return t.limit!==void 0&&c.length>t.limit&&(c=c.slice(c.length-t.limit)),c}async search(e,t,o={}){let n=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
606
606
  SELECT m.id, m.conversation_id, m.participant_kind, m.participant_id, m.participant_display_name,
607
607
  m.content, m.timestamp, m.scope, m.metadata
608
608
  FROM messages m
@@ -613,21 +613,21 @@ Execute this plan now.
613
613
  content, timestamp, scope, metadata
614
614
  FROM messages
615
615
  WHERE conversation_id = ? AND content LIKE ? COLLATE NOCASE
616
- ORDER BY timestamp DESC`).all(e,`%${t}%`);let a=i.map(m=>this.rowToMessage(m)),l=[],p=0;for(let m of a){if(l.length>=n)break;let d=Math.ceil(m.content.length/4);if(l.length>0&&p+d>s)break;l.push(m),p+=d}return l}async deleteMessages(e,t){if(!t||t.length===0)return;let o=t.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${o})`).run(e,...t),this.useFTS){let s=t.map(l=>`${e}:${l}`),i=s.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${i})`).run(...s)}}clearConversation(e){this.useFTS&&this.db.prepare("DELETE FROM messages_fts WHERE doc_key LIKE ?").run(`${e}:%`),this.db.prepare("DELETE FROM messages WHERE conversation_id = ?").run(e)}rowToMessage(e){return{id:e.id,conversationId:e.conversation_id,participant:{kind:e.participant_kind,id:e.participant_id,displayName:e.participant_display_name??void 0},content:e.content,timestamp:e.timestamp,scope:e.scope,metadata:e.metadata?JSON.parse(e.metadata):void 0}}close(){try{this.db.close()}catch{}}};c();import*as Nw from"os";import*as mt from"path";import*as jt from"fs";var Ow=".toolpack",Iw="config",jw="toolpack.config.json";function hk(){return Nw.homedir()}function yk(){return mt.join(hk(),Ow)}function Lw(){return mt.join(yk(),Iw)}function Ur(){return mt.join(Lw(),jw)}function bk(r=process.cwd()){return mt.join(r,Ow)}function Fw(r=process.cwd()){return mt.join(bk(r),Iw)}function Gr(r=process.cwd()){return mt.join(Fw(r),jw)}function qw(){let r=Lw();jt.existsSync(r)||jt.mkdirSync(r,{recursive:!0})}function BB(r=process.cwd()){let e=Fw(r);jt.existsSync(e)||jt.mkdirSync(e,{recursive:!0})}c();import*as ae from"fs";import*as Br from"path";function ma(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]=ma(r[o],e[o]):t[o]=e[o];return t}function pa(r){if(!ae.existsSync(r))return null;try{let e=ae.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function VB(r=process.cwd()){let e=Br.join(r,"toolpack.config.json"),t=Ur(),o=Gr(r),n=pa(e)||{},s=pa(t)||{},i=pa(o)||{},a=ma(n,s);return a=ma(a,i),a}function QB(r=process.cwd()){let e=Br.join(r,"toolpack.config.json"),t=Ur(),o=Gr(r),n=!ae.existsSync(t),s=null,i="default";return ae.existsSync(o)?(s=o,i="local"):ae.existsSync(t)?(s=t,i="global"):ae.existsSync(e)&&(s=e,i="base"),{isFirstRun:n,activeConfigPath:s,configSource:i}}function XB(r=process.cwd()){let e=Ur();if(!ae.existsSync(e)){qw();let t=null,o=Gr(r);if(ae.existsSync(o))t=o;else{let s=Br.join(r,"toolpack.config.json");if(ae.existsSync(s))t=s;else{let i=ot();i&&ae.existsSync(i)&&(t=i)}}let n={};if(t)try{let s=ae.readFileSync(t,"utf-8");n=JSON.parse(s)}catch{}ae.writeFileSync(e,JSON.stringify(n,null,4),"utf-8")}}c();c();c();import*as Qe from"fs/promises";import*as Lt from"path";c();var wk=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"]),zr=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.replace(/([a-z])([A-Z])/g,"$1 $2");return t=t.toLowerCase(),t=t.replace(/[^a-z0-9]/g," "),t.split(/\s+/).filter(o=>o.length>1).filter(o=>!wk.has(o))}addDocument(e,t){this.documents.set(e,t);let o=this.tokenize(t);this.documentLengths.set(e,o.length);let n={};for(let s of o)n[s]=(n[s]??0)+1;for(let[s,i]of Object.entries(n))this.termFrequencies.has(s)||this.termFrequencies.set(s,new Map),this.termFrequencies.get(s).set(e,i);this.updateAvgDocLength()}clear(){this.documents.clear(),this.termFrequencies.clear(),this.documentLengths.clear(),this.avgDocLength=0}get size(){return this.documents.size}updateAvgDocLength(){if(this.documentLengths.size===0){this.avgDocLength=0;return}let e=0;this.documentLengths.forEach(t=>{e+=t}),this.avgDocLength=e/this.documentLengths.size}idf(e){let t=this.documents.size,o=this.termFrequencies.get(e)?.size??0;return o===0?0:Math.log((t-o+.5)/(o+.5)+1)}search(e,t=10){let o=this.tokenize(e);if(o.length===0)return[];let n={};this.documents.forEach((i,a)=>{let l=0,p=this.documentLengths.get(a)??0;for(let m of o){let d=this.termFrequencies.get(m);if(!d)continue;let g=d.get(a)??0;if(g===0)continue;let b=this.idf(m),w=g*(this.k1+1),T=g+this.k1*(1-this.b+this.b*(p/this.avgDocLength));l+=b*(w/T)}l>0&&(n[a]=l)});let s=Object.entries(n).map(([i,a])=>({id:i,score:a}));return s.sort((i,a)=>a.score-i.score),s.slice(0,t)}};c();import*as Ve from"path";function Ww(r,e,t){let o=r.match(/^---\n([\s\S]*?)\n---/),n="",s="",i,a=[];if(o&&o[1]){let D=o[1].split(`
617
- `),M=!1;for(let k of D){if(M){let N=k.match(/^\s+-\s+(.+?)\s*$/);if(N){a.push(N[1].replace(/^["']|["']$/g,""));continue}M=!1}let $=k.indexOf(":");if($===-1)continue;let E=k.substring(0,$).trim(),R=k.substring($+1).trim();if(E==="name"&&(n=R),E==="title"&&(s=R),E==="version"&&(i=R),E==="tags")if(R){let N=R.match(/\[([^\]]*)\]/);N&&(a=N[1].split(",").map(ue=>ue.trim().replace(/^["']|["']$/g,"")).filter(Boolean))}else M=!0,a=[]}}n||(n=Ve.basename(e,".skill.md"));let l=r.match(/## Description\n\n([\s\S]*?)(?=\n## |$)/),p=l&&l[1]?l[1].trim():"",m=r.match(/## Triggers\n\n([\s\S]*?)(?=\n## |$)/),d=[];if(m&&m[1]){let D=m[1].split(`
618
- `).filter(M=>M.startsWith("- "));for(let M of D){let k=M.match(/^- "(.*)"/);k&&k[1]&&d.push(k[1])}}let g=r.match(/## Instructions\n\n([\s\S]*?)(?=\n## |$)/),b=g&&g[1]?g[1].trim():"",w=r.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/),T=w&&w[1]?w[1].trim():void 0,v=Ve.relative(t,e),C=Ve.dirname(v),x=C==="."?void 0:C.split(Ve.sep)[0];return{name:n,title:s,version:i,tags:a,category:x,filePath:e,description:p,triggers:d,instructions:b,examples:T||void 0,lastModified:0}}c();c();var H={name:50,title:100,tags:{count:10,each:30},description:300,triggers:{count:10,min:1,each:100},instructions:5e3,examples:3e3};var Tk=/^[a-z][a-z0-9-]*$/;function Uw(r,e){let t=[],o=[];r.name?(Tk.test(r.name)||t.push(`name "${r.name}" must match kebab-case pattern /^[a-z][a-z0-9-]*$/`),r.name.length>H.name&&o.push(`name exceeds ${H.name} character limit (${r.name.length} chars)`)):t.push("name is required in frontmatter"),r.title?r.title.length>H.title&&o.push(`title exceeds ${H.title} character limit (${r.title.length} chars)`):t.push("title is required in frontmatter"),r.tags.length>H.tags.count&&o.push(`too many tags (${r.tags.length}); maximum is ${H.tags.count}`);for(let n of r.tags)n.length>H.tags.each&&o.push(`tag "${n}" exceeds ${H.tags.each} character limit`);if(r.description?r.description.length>H.description&&o.push(`description exceeds ${H.description} character limit (${r.description.length} chars)`):t.push("## Description section is required and must not be empty"),!r.triggers||r.triggers.length===0)t.push("## Triggers section must contain at least one trigger");else{r.triggers.length<3&&o.push(`only ${r.triggers.length} trigger(s) defined; add more variations (synonyms, short forms, longer phrases) so BM25 can match a wider range of user phrasings \u2014 aim for at least 3`),r.triggers.length>H.triggers.count&&o.push(`too many triggers (${r.triggers.length}); maximum is ${H.triggers.count}`);for(let n of r.triggers)n.length>H.triggers.each&&o.push(`trigger "${n.substring(0,50)}..." exceeds ${H.triggers.each} character limit`)}return r.instructions?r.instructions.length>H.instructions&&o.push(`instructions exceed ${H.instructions} character limit (${r.instructions.length} chars)`):t.push("## Instructions section is required and must not be empty"),r.examples&&r.examples.length>H.examples&&o.push(`examples exceed ${H.examples} character limit (${r.examples.length} chars)`),{file:e,errors:t,warnings:o}}var Hr=class{dir;onValidationError;loaded=!1;skills=new Map;fileMtimes=new Map;index=new zr;_buildPromise=null;constructor(e){this.dir=Lt.resolve(e.dir),this.onValidationError=e.onValidationError}async findSkillFiles(e){let t=[],o;try{o=await Qe.readdir(e)}catch{return t}for(let n of o){let s=Lt.join(e,n),i;try{i=await Qe.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 Qe.stat(t),n=this.fileMtimes.get(t);if(n===void 0||o.mtimeMs!==n)return!0}catch{return!0}return!1}async buildIndex(e){this.loaded=!1,this.skills.clear(),this.fileMtimes.clear(),this.index.clear();let t=[],o=[],n=new Map;for(let s of e){let i,a;try{let[g,b]=await Promise.all([Qe.readFile(s,"utf-8"),Qe.stat(s)]);i=g.replace(/\r\n/g,`
619
- `),a=b.mtimeMs}catch{continue}this.fileMtimes.set(s,a);let l=Ww(i,s,this.dir);l.lastModified=a;let p=Lt.relative(this.dir,s),m=Uw(l,p);if(m.warnings.length>0)for(let g of m.warnings)console.warn(`[skills] ${p}: ${g}`);if(m.errors.length>0){t.push({file:p,errors:m.errors}),this.onValidationError==="warn"&&console.warn(`[skills] Skipping invalid skill "${p}": ${m.errors.join("; ")}`);continue}let d=n.get(l.name);if(d){let g=`duplicate skill name "${l.name}" \u2014 already defined in "${d}"`;t.push({file:p,errors:[g]}),this.onValidationError==="warn"&&console.warn(`[skills] Skipping "${p}": ${g}`);continue}n.set(l.name,p),o.push(l)}if(t.length>0&&this.onValidationError==="fail"){let s=t.map(i=>` ${i.file}:
616
+ 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 d=Math.ceil(m.content.length/4);if(c.length>0&&p+d>s)break;c.push(m),p+=d}return c}async deleteMessages(e,t){if(!t||t.length===0)return;let o=t.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${o})`).run(e,...t),this.useFTS){let s=t.map(c=>`${e}:${c}`),i=s.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${i})`).run(...s)}}clearConversation(e){this.useFTS&&this.db.prepare("DELETE FROM messages_fts WHERE doc_key LIKE ?").run(`${e}:%`),this.db.prepare("DELETE FROM messages WHERE conversation_id = ?").run(e)}rowToMessage(e){return{id:e.id,conversationId:e.conversation_id,participant:{kind:e.participant_kind,id:e.participant_id,displayName:e.participant_display_name??void 0},content:e.content,timestamp:e.timestamp,scope:e.scope,metadata:e.metadata?JSON.parse(e.metadata):void 0}}close(){try{this.db.close()}catch{}}};l();import*as Pw from"os";import*as mt from"path";import*as Ot from"fs";var _w=".toolpack",Rw="config",$w="toolpack.config.json";function ak(){return Pw.homedir()}function lk(){return mt.join(ak(),_w)}function Ew(){return mt.join(lk(),Rw)}function Or(){return mt.join(Ew(),$w)}function ck(r=process.cwd()){return mt.join(r,_w)}function Dw(r=process.cwd()){return mt.join(ck(r),Rw)}function Ir(r=process.cwd()){return mt.join(Dw(r),$w)}function Mw(){let r=Ew();Ot.existsSync(r)||Ot.mkdirSync(r,{recursive:!0})}function BB(r=process.cwd()){let e=Dw(r);Ot.existsSync(e)||Ot.mkdirSync(e,{recursive:!0})}l();import*as ce from"fs";import*as Lr from"path";function sa(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]=sa(r[o],e[o]):t[o]=e[o];return t}function ra(r){if(!ce.existsSync(r))return null;try{let e=ce.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function VB(r=process.cwd()){let e=Lr.join(r,"toolpack.config.json"),t=Or(),o=Ir(r),n=ra(e)||{},s=ra(t)||{},i=ra(o)||{},a=sa(n,s);return a=sa(a,i),a}function QB(r=process.cwd()){let e=Lr.join(r,"toolpack.config.json"),t=Or(),o=Ir(r),n=!ce.existsSync(t),s=null,i="default";return ce.existsSync(o)?(s=o,i="local"):ce.existsSync(t)?(s=t,i="global"):ce.existsSync(e)&&(s=e,i="base"),{isFirstRun:n,activeConfigPath:s,configSource:i}}function XB(r=process.cwd()){let e=Or();if(!ce.existsSync(e)){Mw();let t=null,o=Ir(r);if(ce.existsSync(o))t=o;else{let s=Lr.join(r,"toolpack.config.json");if(ce.existsSync(s))t=s;else{let i=tt();i&&ce.existsSync(i)&&(t=i)}}let n={};if(t)try{let s=ce.readFileSync(t,"utf-8");n=JSON.parse(s)}catch{}ce.writeFileSync(e,JSON.stringify(n,null,4),"utf-8")}}l();l();l();import*as Ve from"fs/promises";import*as It from"path";l();var pk=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"]),jr=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.replace(/([a-z])([A-Z])/g,"$1 $2");return t=t.toLowerCase(),t=t.replace(/[^a-z0-9]/g," "),t.split(/\s+/).filter(o=>o.length>1).filter(o=>!pk.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 d=this.termFrequencies.get(m);if(!d)continue;let g=d.get(a)??0;if(g===0)continue;let w=this.idf(m),b=g*(this.k1+1),T=g+this.k1*(1-this.b+this.b*(p/this.avgDocLength));c+=w*(b/T)}c>0&&(n[a]=c)});let s=Object.entries(n).map(([i,a])=>({id:i,score:a}));return s.sort((i,a)=>a.score-i.score),s.slice(0,t)}};l();import*as Je from"path";function Aw(r,e,t){let o=r.match(/^---\n([\s\S]*?)\n---/),n="",s="",i,a=[];if(o&&o[1]){let C=o[1].split(`
617
+ `),_=!1;for(let E of C){if(_){let G=E.match(/^\s+-\s+(.+?)\s*$/);if(G){a.push(G[1].replace(/^["']|["']$/g,""));continue}_=!1}let $=E.indexOf(":");if($===-1)continue;let te=E.substring(0,$).trim(),F=E.substring($+1).trim();if(te==="name"&&(n=F),te==="title"&&(s=F),te==="version"&&(i=F),te==="tags")if(F){let G=F.match(/\[([^\]]*)\]/);G&&(a=G[1].split(",").map(q=>q.trim().replace(/^["']|["']$/g,"")).filter(Boolean))}else _=!0,a=[]}}n||(n=Je.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## |$)/),d=[];if(m&&m[1]){let C=m[1].split(`
618
+ `).filter(_=>_.startsWith("- "));for(let _ of C){let E=_.match(/^- "(.*)"/);E&&E[1]&&d.push(E[1])}}let g=r.match(/## Instructions\n\n([\s\S]*?)(?=\n## |$)/),w=g&&g[1]?g[1].trim():"",b=r.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/),T=b&&b[1]?b[1].trim():void 0,k=Je.relative(t,e),v=Je.dirname(k),x=v==="."?void 0:v.split(Je.sep)[0];return{name:n,title:s,version:i,tags:a,category:x,filePath:e,description:p,triggers:d,instructions:w,examples:T||void 0,lastModified:0}}l();l();var H={name:50,title:100,tags:{count:10,each:30},description:300,triggers:{count:10,min:1,each:100},instructions:5e3,examples:3e3};var mk=/^[a-z][a-z0-9-]*$/;function Nw(r,e){let t=[],o=[];r.name?(mk.test(r.name)||t.push(`name "${r.name}" must match kebab-case pattern /^[a-z][a-z0-9-]*$/`),r.name.length>H.name&&o.push(`name exceeds ${H.name} character limit (${r.name.length} chars)`)):t.push("name is required in frontmatter"),r.title?r.title.length>H.title&&o.push(`title exceeds ${H.title} character limit (${r.title.length} chars)`):t.push("title is required in frontmatter"),r.tags.length>H.tags.count&&o.push(`too many tags (${r.tags.length}); maximum is ${H.tags.count}`);for(let n of r.tags)n.length>H.tags.each&&o.push(`tag "${n}" exceeds ${H.tags.each} character limit`);if(r.description?r.description.length>H.description&&o.push(`description exceeds ${H.description} character limit (${r.description.length} chars)`):t.push("## Description section is required and must not be empty"),!r.triggers||r.triggers.length===0)t.push("## Triggers section must contain at least one trigger");else{r.triggers.length<3&&o.push(`only ${r.triggers.length} trigger(s) defined; add more variations (synonyms, short forms, longer phrases) so BM25 can match a wider range of user phrasings \u2014 aim for at least 3`),r.triggers.length>H.triggers.count&&o.push(`too many triggers (${r.triggers.length}); maximum is ${H.triggers.count}`);for(let n of r.triggers)n.length>H.triggers.each&&o.push(`trigger "${n.substring(0,50)}..." exceeds ${H.triggers.each} character limit`)}return r.instructions?r.instructions.length>H.instructions&&o.push(`instructions exceed ${H.instructions} character limit (${r.instructions.length} chars)`):t.push("## Instructions section is required and must not be empty"),r.examples&&r.examples.length>H.examples&&o.push(`examples exceed ${H.examples} character limit (${r.examples.length} chars)`),{file:e,errors:t,warnings:o}}var Fr=class{dir;onValidationError;loaded=!1;skills=new Map;fileMtimes=new Map;index=new jr;_buildPromise=null;constructor(e){this.dir=It.resolve(e.dir),this.onValidationError=e.onValidationError}async findSkillFiles(e){let t=[],o;try{o=await Ve.readdir(e)}catch{return t}for(let n of o){let s=It.join(e,n),i;try{i=await Ve.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 Ve.stat(t),n=this.fileMtimes.get(t);if(n===void 0||o.mtimeMs!==n)return!0}catch{return!0}return!1}async buildIndex(e){this.loaded=!1,this.skills.clear(),this.fileMtimes.clear(),this.index.clear();let t=[],o=[],n=new Map;for(let s of e){let i,a;try{let[g,w]=await Promise.all([Ve.readFile(s,"utf-8"),Ve.stat(s)]);i=g.replace(/\r\n/g,`
619
+ `),a=w.mtimeMs}catch{continue}this.fileMtimes.set(s,a);let c=Aw(i,s,this.dir);c.lastModified=a;let p=It.relative(this.dir,s),m=Nw(c,p);if(m.warnings.length>0)for(let g of m.warnings)console.warn(`[skills] ${p}: ${g}`);if(m.errors.length>0){t.push({file:p,errors:m.errors}),this.onValidationError==="warn"&&console.warn(`[skills] Skipping invalid skill "${p}": ${m.errors.join("; ")}`);continue}let d=n.get(c.name);if(d){let g=`duplicate skill name "${c.name}" \u2014 already defined in "${d}"`;t.push({file:p,errors:[g]}),this.onValidationError==="warn"&&console.warn(`[skills] Skipping "${p}": ${g}`);continue}n.set(c.name,p),o.push(c)}if(t.length>0&&this.onValidationError==="fail"){let s=t.map(i=>` ${i.file}:
620
620
  ${i.errors.join(`
621
621
  `)}`).join(`
622
622
  `);throw new Error(`Skills validation failed \u2014 fix the following files before starting:
623
- ${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 xk(r){let e=r?.dir??".toolpack/skills",t=r?.maxSkills??3,o=r?.minScore??.3,n=r?.onValidationError??"fail",s=new Hr({dir:e,onValidationError:n});return Object.assign(async(i,a)=>{let l=i.mode;if(!l||typeof l!="object"||l.skillInterceptor!==!0)return a(i);let p=i.messages??[],m=-1;for(let g=p.length-1;g>=0;g--)if(p[g].role==="user"){m=g;break}let d=p.filter(g=>g.role==="user"&&typeof g.content=="string").slice(-3).map(g=>g.content.trim()).filter(Boolean).join(" ");if(d){let g=await s.search(d,t,o);if(g.length>0){let w=`<skill-instructions>
624
- ${g.map(C=>`--- Skill: ${C.skill.title} ---
625
- ${C.skill.instructions.trim()}
623
+ ${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 dk(r){let e=r?.dir??".toolpack/skills",t=r?.maxSkills??3,o=r?.minScore??.3,n=r?.onValidationError??"fail",s=new Fr({dir:e,onValidationError:n});return Object.assign(async(i,a)=>{let c=i.mode;if(!c||typeof c!="object"||c.skillInterceptor!==!0)return a(i);let p=i.messages??[],m=-1;for(let g=p.length-1;g>=0;g--)if(p[g].role==="user"){m=g;break}let d=p.filter(g=>g.role==="user"&&typeof g.content=="string").slice(-3).map(g=>g.content.trim()).filter(Boolean).join(" ");if(d){let g=await s.search(d,t,o);if(g.length>0){let b=`<skill-instructions>
624
+ ${g.map(v=>`--- Skill: ${v.skill.title} ---
625
+ ${v.skill.instructions.trim()}
626
626
  ---`).join(`
627
627
 
628
628
  `)}
629
- </skill-instructions>`,T=p.findIndex(C=>C.role==="system"),v;return T>=0&&typeof p[T].content=="string"?v=p.map((C,x)=>x===T?{...C,content:`${C.content}
629
+ </skill-instructions>`,T=p.findIndex(v=>v.role==="system"),k;return T>=0&&typeof p[T].content=="string"?k=p.map((v,x)=>x===T?{...v,content:`${v.content}
630
630
 
631
- ${w}`}:C):T<0?v=[{role:"system",content:w},...p]:v=p.map((C,x)=>x===m&&typeof C.content=="string"?{...C,content:`${w}
631
+ ${b}`}:v):T<0?k=[{role:"system",content:b},...p]:k=p.map((v,x)=>x===m&&typeof v.content=="string"?{...v,content:`${b}
632
632
 
633
- ${C.content}`}:C),a({...i,messages:v})}}return a(i)},{init:()=>s.ensureLoaded()})}export{vw as AGENT_MODE,na as AGENT_PLANNING_PROMPT,ww as AGENT_WORKFLOW,$n as AIClient,En as AnthropicAdapter,Dn as AnthropicVertexAdapter,he as AuthenticationError,Ut as BM25SearchEngine,Fr as BUILT_IN_MODES,Cw as CHAT_MODE,xw as CHAT_WORKFLOW,kw as CODING_MODE,XC as CODING_PLANNING_PROMPT,Tw as CODING_WORKFLOW,Iw as CONFIG_DIR_NAME,jw as CONFIG_FILE_NAME,Xe as ConnectionError,ha as ContextWindowConfigError,Kr as ContextWindowExceededError,es as ContextWindowStateManager,ya as ConversationNotFoundError,Ot as DEFAULT_MODE_NAME,ce as DEFAULT_TOOLS_CONFIG,sT as DEFAULT_TOOL_SEARCH_CONFIG,vG as DEFAULT_WORKFLOW,ra as DEFAULT_WORKFLOW_CONFIG,An as GeminiAdapter,la as InMemoryConversationStore,Jr as InsufficientContextError,O as InvalidRequestError,Cn as McpClient,Ne as McpConnectionError,jr as McpTimeoutError,Lr as McpToolManager,kn as ModeRegistry,nt as OllamaAdapter,Xt as OllamaProvider,Ct as OpenAIAdapter,In as OpenRouterAdapter,fa as PageError,Sn as Planner,ee as ProviderAdapter,F as ProviderError,re as RateLimitError,xt as RuleLoader,j as SDKError,ca as SQLiteConversationStore,Vr as SummarizationError,Ow as TOOLPACK_DIR_NAME,Ye as TOOL_SEARCH_NAME,ga as TimeoutError,ht as ToolDiscoveryCache,vn as ToolRegistry,Bt as ToolRouter,Aw as Toolpack,Mn as VertexAIAdapter,qr as WorkflowExecutor,PT as addBypassRule,Kk as buildSummarizedHistory,Cr as cloudDeployTool,Sr as cloudListTool,kr as cloudStatusTool,Rb as cloudToolsProject,un as codingExtractFunctionTool,sn as codingFindReferencesTool,on as codingFindSymbolTool,fn as codingGetCallHierarchyTool,mn as codingGetDiagnosticsTool,dn as codingGetExportsTool,rn as codingGetImportsTool,pn as codingGetOutlineTool,nn as codingGetSymbolsTool,an as codingGoToDefinitionTool,ln as codingMultiFileEditTool,cn as codingRefactorRenameTool,Qh as codingToolsProject,Ta as countTokens,Pa as createContextWindowStateManager,Yi as createMcpToolProject,YC as createMode,xk as createSkillInterceptor,QC as createSkillTools,Jk as createSummarizationReport,Zr as createSummarySystemMessage,WC as createToolProject,xr as dbCountTool,Tr as dbDeleteTool,br as dbInsertTool,gr as dbQueryTool,hr as dbSchemaTool,yr as dbTablesTool,yb as dbToolsProject,wr as dbUpdateTool,pr as diffApplyTool,cr as diffCreateTool,mr as diffPreviewTool,By as diffToolsProject,Zi as disconnectMcpToolProject,qw as ensureGlobalConfigDir,BB as ensureLocalConfigDir,oT as estimateSummaryTokens,je as estimateTokenCount,ko as execKillTool,So as execListProcessesTool,vo as execReadOutputTool,To as execRunBackgroundTool,xo as execRunBlockingTool,wo as execRunShellTool,bo as execRunTool,Co as execTailOutputTool,fm as execToolsProject,Hk as extractConversationKeypoints,Ka as fetchUrlAsBase64,eo as fsAppendFileTool,ho as fsBatchReadTool,yo as fsBatchWriteTool,lo as fsCopyTool,so as fsCreateDirTool,go as fsDeleteDirTool,to as fsDeleteFileTool,oo as fsExistsTool,fo as fsGlobTool,ro as fsListDirTool,io as fsMoveTool,co as fsReadFileRangeTool,Yt as fsReadFileTool,mo as fsReplaceInFileTool,po as fsSearchTool,no as fsStatTool,gp as fsToolsProject,uo as fsTreeTool,Zt as fsWriteFileTool,tT as generateSummarizationPrompt,ts as generateToolCategoriesPrompt,jk as getContextWindowPercentage,RT as getDefaultSlmModel,Lw as getGlobalConfigDir,Ur as getGlobalConfigPath,yk as getGlobalToolpackDir,Fw as getLocalConfigDir,Gr as getLocalConfigPath,bk as getLocalToolpackDir,Uk as getMessageStats,Ga as getMimeType,On as getOllamaBaseUrl,ST as getOllamaProviderEntries,ET as getRegisteredSlmModels,QB as getRuntimeConfigStatus,xa as getSafeOutputReserve,Ze as getToolSearchSchema,is as getToolpackConfig,hk as getUserHomeDir,er as gitAddTool,or as gitBlameTool,rr as gitBranchCreateTool,nr as gitBranchListTool,sr as gitCheckoutTool,lr as gitCloneTool,tr as gitCommitTool,Yn as gitDiffTool,Zn as gitLogTool,Xn as gitStatusTool,$y as gitToolsProject,jo as githubContentsGetTextTool,Io as githubGraphqlExecuteTool,Bo as githubIssuesCommentsCreateTool,Wo as githubPrDiffGetTool,Uo as githubPrFilesListTool,qo as githubPrReviewCommentsReplyTool,Lo as githubPrReviewThreadsListTool,Fo as githubPrReviewThreadsResolveTool,Go as githubPrReviewsSubmitTool,Lu as githubToolsProject,Wk as groupMessagesByRole,_k as handleContextWindowError,No as httpDeleteTool,Oo as httpDownloadTool,Do as httpGetTool,Mo as httpPostTool,Ao as httpPutTool,Md as httpToolsProject,XB as initializeGlobalConfigIfFirstRun,Pk as isContextWindowError,Ba as isDataUri,$T as isRegisteredSlm,bt as isToolSearchTool,$r as k8sApplyManifestTool,Er as k8sDeleteResourceTool,_r as k8sDescribeTool,Ar as k8sGetConfigMapTool,Rr as k8sGetLogsTool,Or as k8sGetNamespacesTool,Mr as k8sListDeploymentsTool,Pr as k8sListPodsTool,Dr as k8sListServicesTool,Nr as k8sSwitchContextTool,hw as k8sToolsProject,Ir as k8sWaitForDeploymentTool,Gn as loadFullConfig,VB as loadRuntimeConfig,Ho as loadToolsConfig,Vk as mergeSummarizationResults,wT as normalizeImagePart,Re as ollamaRequest,ls as ollamaStream,za as parseDataUri,Sa as parseSummarizationResponse,ka as prepareSummarizationRequest,va as pruneMessages,Ha as readFileAsBase64,as as reloadToolpackConfig,_T as removeBypassRule,Gx as saveToolsConfig,xn as slackAuthTestTool,yn as slackChatPostEphemeralTool,hn as slackChatPostMessageTool,wn as slackConversationsHistoryTool,Tn as slackConversationsRepliesTool,bn as slackReactionsAddTool,dw as slackToolsProject,$o as systemCwdTool,Eo as systemDiskUsageTool,_o as systemEnvTool,Po as systemInfoTool,Ro as systemSetEnvTool,Vm as systemToolsProject,bT as toDataUri,yt as toolSearchDefinition,qk as truncateMessage,Ca as validateSummarizationResult,Vo as webExtractLinksTool,Zo as webFeedTool,zo as webFetchTool,Qo as webMapTool,Xo as webMetadataTool,Jo as webScrapeTool,en as webScreenshotTool,Ko as webSearchTool,Yo as webSitemapTool,ag as webToolsProject,Ik as wouldExceedContextWindow};
633
+ ${v.content}`}:v),a({...i,messages:k})}}return a(i)},{init:()=>s.ensureLoaded()})}export{fw as AGENT_MODE,Xi as AGENT_PLANNING_PROMPT,mw as AGENT_WORKFLOW,Sn as AIClient,Pn as AnthropicAdapter,_n as AnthropicVertexAdapter,ge as AuthenticationError,qt as BM25SearchEngine,Mr as BUILT_IN_MODES,gw as CHAT_MODE,uw as CHAT_WORKFLOW,hw as CODING_MODE,UC as CODING_PLANNING_PROMPT,dw as CODING_WORKFLOW,Rw as CONFIG_DIR_NAME,$w as CONFIG_FILE_NAME,Qe as ConnectionError,pa as ContextWindowConfigError,qr as ContextWindowExceededError,Kr as ContextWindowStateManager,ma as ConversationNotFoundError,At as DEFAULT_MODE_NAME,ne as DEFAULT_TOOLS_CONFIG,Xw as DEFAULT_TOOL_SEARCH_CONFIG,TG as DEFAULT_WORKFLOW,Yi as DEFAULT_WORKFLOW_CONFIG,$n as GeminiAdapter,oa as InMemoryConversationStore,Wr as InsufficientContextError,M as InvalidRequestError,wn as McpClient,Oe as McpConnectionError,Er as McpTimeoutError,Dr as McpToolManager,Tn as ModeRegistry,ot as OllamaAdapter,zt as OllamaProvider,Ct as OpenAIAdapter,Mn as OpenRouterAdapter,la as PageError,xn as Planner,ee as ProviderAdapter,I as ProviderError,ie as RateLimitError,xt as RuleLoader,N as SDKError,na as SQLiteConversationStore,Ur as SummarizationError,_w as TOOLPACK_DIR_NAME,Xe as TOOL_SEARCH_NAME,ca as TimeoutError,ht as ToolDiscoveryCache,bn as ToolRegistry,Ut as ToolRouter,Sw as Toolpack,Rn as VertexAIAdapter,Ar as WorkflowExecutor,TT as addBypassRule,jk as buildSummarizedHistory,gr as cloudDeployTool,yr as cloudListTool,hr as cloudStatusTool,yb as cloudToolsProject,cn as codingExtractFunctionTool,tn as codingFindReferencesTool,Yo as codingFindSymbolTool,pn as codingGetCallHierarchyTool,an as codingGetDiagnosticsTool,ln as codingGetExportsTool,en as codingGetImportsTool,sn as codingGetOutlineTool,Zo as codingGetSymbolsTool,on as codingGoToDefinitionTool,nn as codingMultiFileEditTool,rn as codingRefactorRenameTool,Fh as codingToolsProject,fa as countTokens,Ta as createContextWindowStateManager,Hi as createMcpToolProject,GC as createMode,dk as createSkillInterceptor,WC as createSkillTools,Fk as createSummarizationReport,Hr as createSummarySystemMessage,MC as createToolProject,ur as dbCountTool,dr as dbDeleteTool,pr as dbInsertTool,ar as dbQueryTool,lr as dbSchemaTool,cr as dbTablesTool,ib as dbToolsProject,mr as dbUpdateTool,or as diffApplyTool,tr as diffCreateTool,nr as diffPreviewTool,Ay as diffToolsProject,Ki as disconnectMcpToolProject,Mw as ensureGlobalConfigDir,BB as ensureLocalConfigDir,Jw as estimateSummaryTokens,je as estimateTokenCount,xo as execKillTool,vo as execListProcessesTool,wo as execReadOutputTool,yo as execRunBackgroundTool,bo as execRunBlockingTool,ho as execRunShellTool,go as execRunTool,To as execTailOutputTool,cm as execToolsProject,Lk as extractConversationKeypoints,Fa as fetchUrlAsBase64,Xt as fsAppendFileTool,uo as fsBatchReadTool,fo as fsBatchWriteTool,so as fsCopyTool,oo as fsCreateDirTool,mo as fsDeleteDirTool,Yt as fsDeleteFileTool,Zt as fsExistsTool,po as fsGlobTool,to as fsListDirTool,no as fsMoveTool,io as fsReadFileRangeTool,Vt as fsReadFileTool,lo as fsReplaceInFileTool,ao as fsSearchTool,eo as fsStatTool,up as fsToolsProject,co as fsTreeTool,Qt as fsWriteFileTool,Kw as generateSummarizationPrompt,Jr as generateToolCategoriesPrompt,Rk as getContextWindowPercentage,vT as getDefaultSlmModel,Ew as getGlobalConfigDir,Or as getGlobalConfigPath,lk as getGlobalToolpackDir,Dw as getLocalConfigDir,Ir as getLocalConfigPath,ck as getLocalToolpackDir,Ak as getMessageStats,Oa as getMimeType,Dn as getOllamaBaseUrl,wT as getOllamaProviderEntries,kT as getRegisteredSlmModels,QB as getRuntimeConfigStatus,ga as getSafeOutputReserve,Ye as getToolSearchSchema,Zr as getToolpackConfig,ak as getUserHomeDir,Kn as gitAddTool,Vn as gitBlameTool,Xn as gitBranchCreateTool,Qn as gitBranchListTool,Yn as gitCheckoutTool,er as gitCloneTool,Jn as gitCommitTool,zn as gitDiffTool,Hn as gitLogTool,Bn as gitStatusTool,by as gitToolsProject,No as githubContentsGetTextTool,Ao as githubGraphqlExecuteTool,Wo as githubIssuesCommentsCreateTool,jo as githubPrDiffGetTool,Fo as githubPrFilesListTool,Lo as githubPrReviewCommentsReplyTool,Oo as githubPrReviewThreadsListTool,Io as githubPrReviewThreadsResolveTool,qo as githubPrReviewsSubmitTool,$u as githubToolsProject,Mk as groupMessagesByRole,bk as handleContextWindowError,Do as httpDeleteTool,Mo as httpDownloadTool,Ro as httpGetTool,$o as httpPostTool,Eo as httpPutTool,_d as httpToolsProject,XB as initializeGlobalConfigIfFirstRun,yk as isContextWindowError,Ia as isDataUri,CT as isRegisteredSlm,bt as isToolSearchTool,xr as k8sApplyManifestTool,vr as k8sDeleteResourceTool,wr as k8sDescribeTool,Sr as k8sGetConfigMapTool,Tr as k8sGetLogsTool,_r as k8sGetNamespacesTool,kr as k8sListDeploymentsTool,br as k8sListPodsTool,Cr as k8sListServicesTool,Pr as k8sSwitchContextTool,sw as k8sToolsProject,Rr as k8sWaitForDeploymentTool,lw as loadFullConfig,VB as loadRuntimeConfig,$C as loadToolsConfig,qk as mergeSummarizationResults,dT as normalizeImagePart,Re as ollamaRequest,es as ollamaStream,La as parseDataUri,wa as parseSummarizationResponse,ba as prepareSummarizationRequest,ha as pruneMessages,ja as readFileAsBase64,bT as reloadToolpackConfig,xT as removeBypassRule,EC as saveToolsConfig,yn as slackAuthTestTool,un as slackChatPostEphemeralTool,dn as slackChatPostMessageTool,gn as slackConversationsHistoryTool,hn as slackConversationsRepliesTool,fn as slackReactionsAddTool,tw as slackToolsProject,Po as systemCwdTool,_o as systemDiskUsageTool,ko as systemEnvTool,Co as systemInfoTool,So as systemSetEnvTool,Bm as systemToolsProject,mT as toDataUri,yt as toolSearchDefinition,Dk as truncateMessage,ya as validateSummarizationResult,zo as webExtractLinksTool,Vo as webFeedTool,Uo as webFetchTool,Ho as webMapTool,Ko as webMetadataTool,Bo as webScrapeTool,Qo as webScreenshotTool,Go as webSearchTool,Jo as webSitemapTool,Qf as webToolsProject,_k as wouldExceedContextWindow};