toolpack-sdk 3.2.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- var ET=Object.defineProperty;var h=(r,e)=>()=>(r&&(e=r(r=0)),e);var te=(r,e)=>{for(var t in e)ET(r,t,{get:e[t],enumerable:!0})};import DT from"path";import{fileURLToPath as MT}from"url";var AT,NT,u,l=h(()=>{"use strict";AT=()=>MT(import.meta.url),NT=()=>DT.dirname(AT()),u=NT()});function uk(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 fk(r,e){return r instanceof jr?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof Or?{shouldRetry:!1,shouldFallback:!0,action:r.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${r.strategy}`}:r instanceof Ir?{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,fe,se,M,I,Ve,ra,sa,Or,Ir,jr,ia,aa,ie=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},fe=class extends N{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},se=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"}},Ve=class extends N{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},ra=class extends N{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},sa=class extends N{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},Or=class extends N{constructor(t,o,n,s,i,a){super(t,"CONTEXT_WINDOW_EXCEEDED",400,a);this.conversationId=o;this.currentTokens=n;this.contextWindowLimit=s;this.strategy=i;this.name="ContextWindowExceededError"}conversationId;currentTokens;contextWindowLimit;strategy;getOverageTokens(){return Math.max(0,this.currentTokens-this.contextWindowLimit)}getUsagePercentage(){return Math.round(this.currentTokens/this.contextWindowLimit*100)}getDetailedReport(){return`
1
+ var OT=Object.defineProperty;var h=(r,e)=>()=>(r&&(e=r(r=0)),e);var re=(r,e)=>{for(var t in e)OT(r,t,{get:e[t],enumerable:!0})};import IT from"path";import{fileURLToPath as jT}from"url";var LT,FT,u,l=h(()=>{"use strict";LT=()=>jT(import.meta.url),FT=()=>IT.dirname(LT()),u=FT()});function bk(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 Tk(r,e){return r instanceof Wr?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof Fr?{shouldRetry:!1,shouldFallback:!0,action:r.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${r.strategy}`}:r instanceof qr?{shouldRetry:!1,shouldFallback:!0,action:"fail",message:"Insufficient context after recovery attempts"}:{shouldRetry:!1,shouldFallback:!1,action:"none",message:"Unknown context window error"}}var I,ye,ce,N,L,tt,ca,pa,Fr,qr,Wr,ma,da,pe=h(()=>{"use strict";l();I=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},ye=class extends I{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},ce=class extends I{constructor(t,o,n){super(t,"RATE_LIMIT_ERROR",429,n);this.retryAfter=o;this.name="RateLimitError"}retryAfter},N=class extends I{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},L=class extends I{constructor(e,t="PROVIDER_ERROR",o=500,n){super(e,t,o,n),this.name="ProviderError"}},tt=class extends I{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},ca=class extends I{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},pa=class extends I{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},Fr=class extends I{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()}},Ir=class extends N{constructor(t,o,n,s,i,a){super(t,"INSUFFICIENT_CONTEXT",400,a);this.conversationId=o;this.requiredTokens=n;this.availableTokens=s;this.minimumRequiredTokens=i;this.name="InsufficientContextError"}conversationId;requiredTokens;availableTokens;minimumRequiredTokens;getDeficit(){return Math.max(0,this.requiredTokens-this.availableTokens)}isRecoverable(){return this.availableTokens>=this.minimumRequiredTokens*.5}getDetailedReport(){return`
12
+ `.trim()}},qr=class extends I{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()}},jr=class extends N{constructor(t,o,n,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=n;this.failureReason=s;this.summaryAttempt=i;this.name="SummarizationError"}conversationId;messageCount;failureReason;summaryAttempt;isRetryable(){return this.failureReason==="provider_error"||this.failureReason==="insufficient_tokens"}getSuggestedRecovery(){switch(this.failureReason){case"provider_error":return"Retry the summarization request or switch to a different summarizer model";case"invalid_response":return"Review the summarizer prompt or use a different model";case"insufficient_tokens":return"Reduce the number of messages to summarize or increase the summary token budget";case"invalid_quality":return"Adjust summarization parameters or use a more capable model";default:return"Manual intervention required"}}getDetailedReport(){let t=`
23
+ `.trim()}},Wr=class extends I{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()}},ia=class extends N{constructor(t,o,n,s,i){super(t,"CONTEXT_WINDOW_CONFIG_ERROR",400,i);this.configField=o;this.providedValue=n;this.constraint=s;this.name="ContextWindowConfigError"}configField;providedValue;constraint;getDetailedReport(){return`
35
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}},ma=class extends I{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()}},aa=class extends N{constructor(t,o,n){super(t,"CONVERSATION_NOT_FOUND",404,n);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var gt,Lt,GT,ya=h(()=>{"use strict";l();gt={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},Lt=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=>!GT.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}}},GT=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,ba=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 Xe(r){let e=r?.length?{...Le.parameters,properties:{...Le.parameters.properties,category:{type:"string",description:"Optional: filter by category",enum:r}}}:Le.parameters;return{name:Le.name,displayName:Le.displayName,description:Le.description,parameters:e,category:Le.category}}function yt(r){return r===Qe}var Qe,Le,Ta=h(()=>{"use strict";l();Qe="tool.search",Le={name:Qe,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
43
+ `.trim()}},da=class extends I{constructor(t,o,n){super(t,"CONVERSATION_NOT_FOUND",404,n);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var wt,Ut,JT,va=h(()=>{"use strict";l();wt={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 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:d})=>({toolName:c,score:p,tool:this.toSchema(d)}))}getIndexedCount(){return this.documents.length}isIndexed(e){return this.documents.some(t=>t.toolName===e)}createDocument(e){let t=[];for(let i=0;i<wt.name;i++)t.push(e.name);for(let i=0;i<wt.displayName;i++)t.push(e.displayName);for(let i=0;i<wt.description;i++)t.push(e.description);for(let i=0;i<wt.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<wt.parameterNames;c++)t.push(i);if(a.description)for(let c=0;c<wt.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=>!JT.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}}},JT=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 xt,Ca=h(()=>{"use strict";l();xt=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 nt(r){let e=r?.length?{...Be.parameters,properties:{...Be.parameters.properties,category:{type:"string",description:"Optional: filter by category",enum:r}}}:Be.parameters;return{name:Be.name,displayName:Be.displayName,description:Be.description,parameters:e,category:Be.category}}function vt(r){return r===ot}var ot,Be,ka=h(()=>{"use strict";l();ot="tool.search",Be={name:ot,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","http","web","github","slack","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}}});function Gr(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=BT[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 BT,wa=h(()=>{"use strict";l();BT={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 Ft=h(()=>{"use strict";l();ya();ba();Ta();wa()});import{appendFileSync as va,mkdirSync as HT}from"fs";import{dirname as KT,isAbsolute as JT,join as VT,resolve as QT}from"path";function Ca(r){if(!r)return;let e=r.toLowerCase();if(e in Br)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function ka(r){Ze.init(r)}function Tt(r){return Ze.shouldLog(r)}function pe(r){Ze.error(r)}function O(r){Ze.warn(r)}function P(r){Ze.info(r)}function y(r){Ze.debug(r)}function Fe(r){Ze.trace(r)}function Sa(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=Sa(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function Y(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 Br,zr,Ze,S=h(()=>{"use strict";l();Br={error:0,warn:1,info:2,debug:3,trace:4},zr=class{_enabled=!1;_level="info";_logFile=VT(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=Ca(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=Ca(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=JT(this._logFile)?this._logFile:QT(process.cwd(),this._logFile),HT(KT(this._logFile),{recursive:!0}),va(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&&Br[e]<=Br[this._level]}getLevel(){return this._level}write(e,t){if(!this.shouldLog(e))return;let o=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${Sa(t)}`;va(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)}},Ze=new zr});var xt={};te(xt,{fetchUrlAsBase64:()=>Oa,getMimeType:()=>Da,isDataUri:()=>Ma,normalizeImagePart:()=>iw,parseDataUri:()=>Aa,readFileAsBase64:()=>Na,toDataUri:()=>sw});import*as $a from"fs/promises";import*as Ea from"path";function Da(r){let e=Ea.extname(r).toLowerCase();return rw[e]||"application/octet-stream"}function Ma(r){return r.startsWith("data:")}function Aa(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function sw(r,e){return`data:${e};base64,${r}`}async function Na(r){try{return{data:(await $a.readFile(r)).toString("base64"),mimeType:Da(r)}}catch(e){throw new M(`Failed to read image file: ${r}`,e)}}async function Oa(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 iw(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await Na(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(Ma(e)){let t=Aa(e);if(!t)throw new M(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Oa(e)}throw new M(`Unknown ImagePart type: ${r.type}`)}var rw,et=h(()=>{"use strict";l();ie();rw={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Gt,Re,nt=h(()=>{"use strict";l();Gt=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)}},Re=new Gt});import*as za from"fs/promises";var Bt,Ha,Xr=h(()=>{"use strict";l();Bt=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 za.rm(n.cloneDir,{recursive:!0,force:!0}),this.totalBytes=Math.max(0,this.totalBytes-n.sizeBytes),this.registry.delete(s)}catch{break}}}},Ha=new Bt});import*as Ja from"crypto";async function B(r,e,t,o){return(t??Tw).resolve(r,e,o)}function Ka(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=Ja.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var zt,Tw,ye=h(()=>{"use strict";l();zt=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=Ka(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=Ka(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}},Tw=new zt});var Va={};te(Va,{ToolRuntimeContext:()=>Yr});var Yr,Qa=h(()=>{"use strict";l();nt();Xr();ye();Yr=class{processRegistry=new Gt;cloneState=new Bt;githubTokenStore=new zt}});var Xa,Ya,Za,el,tl,ol=h(()=>{"use strict";l();Xa="fs.read_file",Ya="Read File",Za="Read the contents of a file at the given path. Returns the file content as a string.",el="filesystem",tl={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 Ct from"fs";async function ww(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(!Ct.existsSync(e))throw new Error(`File not found: ${e}`);if(Ct.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return Ct.readFileSync(e,t)}var Ht,Zr=h(()=>{"use strict";l();ol();S();Ht={name:Xa,displayName:Ya,description:Za,parameters:tl,category:el,execute:ww}});var nl,rl,sl,il,al,ll=h(()=>{"use strict";l();nl="fs.write_file",rl="Write File",sl="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.",il="filesystem",al={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 kt from"fs";import*as cl from"path";async function xw(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=cl.dirname(e);return kt.existsSync(n)||kt.mkdirSync(n,{recursive:!0}),kt.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var Kt,es=h(()=>{"use strict";l();ll();S();Kt={name:nl,displayName:rl,description:sl,parameters:al,category:il,execute:xw,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var pl,ml,dl,ul,fl,gl=h(()=>{"use strict";l();pl="fs.append_file",ml="Append File",dl="Append content to the end of a file. Creates the file if it does not exist.",ul="filesystem",fl={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 St from"fs";import*as hl from"path";async function vw(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=hl.dirname(e);return St.existsSync(n)||St.mkdirSync(n,{recursive:!0}),St.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Jt,ts=h(()=>{"use strict";l();gl();Jt={name:pl,displayName:ml,description:dl,parameters:fl,category:ul,execute:vw,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var yl,bl,Tl,wl,xl,vl=h(()=>{"use strict";l();yl="fs.delete_file",bl="Delete File",Tl="Remove/delete a file from the filesystem. Does not delete directories.",wl="filesystem",xl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as Pt from"fs";async function Cw(r){let e=r.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Pt.existsSync(e))throw new Error(`File not found: ${e}`);if(Pt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Pt.unlinkSync(e),`File deleted successfully: ${e}`}var Vt,os=h(()=>{"use strict";l();vl();S();Vt={name:yl,displayName:bl,description:Tl,parameters:xl,category:wl,execute:Cw,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var Cl,kl,Sl,Pl,_l,Rl=h(()=>{"use strict";l();Cl="fs.exists",kl="Exists",Sl="Check if a file or directory exists at the given path. Returns true or false.",Pl="filesystem",_l={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as $l from"fs";async function kw(r){let e=r.path;if(!e)throw new Error("path is required");let t=$l.existsSync(e);return JSON.stringify({exists:t,path:e})}var Qt,ns=h(()=>{"use strict";l();Rl();Qt={name:Cl,displayName:kl,description:Sl,parameters:_l,category:Pl,execute:kw}});var El,Dl,Ml,Al,Nl,Ol=h(()=>{"use strict";l();El="fs.stat",Dl="Stat",Ml="Get file or directory information including size, type, and modification date.",Al="filesystem",Nl={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as En from"fs";async function Sw(r){let e=r.path;if(!e)throw new Error("path is required");if(!En.existsSync(e))throw new Error(`Path not found: ${e}`);let t=En.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 Xt,rs=h(()=>{"use strict";l();Ol();Xt={name:El,displayName:Dl,description:Ml,parameters:Nl,category:Al,execute:Sw}});var Il,jl,Ll,Fl,ql,Wl=h(()=>{"use strict";l();Il="fs.list_dir",jl="List Directory",Ll="List files and directories at the given path. Optionally recurse into subdirectories.",Fl="filesystem",ql={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});import*as rt from"fs";import*as Ul from"path";function Gl(r,e,t,o=""){let n=rt.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=Ul.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&Gl(i,!0,t,a);else if(s.isFile()){let c=rt.statSync(i);t.push({name:a,type:"file",size:c.size})}}}async function Pw(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 Gl(e,t,n),JSON.stringify(n,null,2)}var Yt,ss=h(()=>{"use strict";l();Wl();Yt={name:Il,displayName:jl,description:Ll,parameters:ql,category:Fl,execute:Pw}});var Bl,zl,Hl,Kl,Jl,Vl=h(()=>{"use strict";l();Bl="fs.create_dir",zl="Create Directory",Hl="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Kl="filesystem",Jl={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 _t from"fs";async function _w(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(_t.existsSync(e)){if(_t.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return _t.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var Zt,is=h(()=>{"use strict";l();Vl();Zt={name:Bl,displayName:zl,description:Hl,parameters:Jl,category:Kl,execute:_w}});var Ql,Xl,Yl,Zl,ec,tc=h(()=>{"use strict";l();Ql="fs.move",Xl="Move",Yl="Move or rename a file or directory from one path to another.",Zl="filesystem",ec={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 oc from"path";async function Rw(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=oc.dirname(t);return st.existsSync(o)||st.mkdirSync(o,{recursive:!0}),st.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var eo,as=h(()=>{"use strict";l();tc();eo={name:Ql,displayName:Xl,description:Yl,parameters:ec,category:Zl,execute:Rw,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var nc,rc,sc,ic,ac,lc=h(()=>{"use strict";l();nc="fs.copy",rc="Copy",sc="Copy a file or directory from one path to another. Recursively copies directories.",ic="filesystem",ac={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 to from"path";function cc(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)cc(to.join(r,n),to.join(e,n))}else me.copyFileSync(r,e)}async function $w(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=to.dirname(t);return me.existsSync(o)||me.mkdirSync(o,{recursive:!0}),cc(e,t),`Copied ${me.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var oo,ls=h(()=>{"use strict";l();lc();oo={name:nc,displayName:rc,description:sc,parameters:ac,category:ic,execute:$w,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var pc,mc,dc,uc,fc,gc=h(()=>{"use strict";l();pc="fs.read_file_range",mc="Read File Range",dc="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",uc="filesystem",fc={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 Rt from"fs";async function Ew(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(!Rt.existsSync(e))throw new Error(`File not found: ${e}`);if(Rt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=Rt.readFileSync(e,"utf-8").split(`
53
- `),a=i.length,c=Math.min(t,a),p=Math.min(o,a),d=i.slice(c-1,p).map((g,T)=>`${c+T}: ${g}`).join(`
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","http","web","github","slack","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}}});function Kr(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=VT[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 VT,Sa=h(()=>{"use strict";l();VT={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";l();va();Ca();ka();Sa()});import{appendFileSync as Pa,mkdirSync as XT}from"fs";import{dirname as YT,isAbsolute as ZT,join as ew,resolve as tw}from"path";function Ra(r){if(!r)return;let e=r.toLowerCase();if(e in Jr)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function $a(r){st.init(r)}function it(r){return st.shouldLog(r)}function ue(r){st.error(r)}function M(r){st.warn(r)}function S(r){st.info(r)}function b(r){st.debug(r)}function ze(r){st.trace(r)}function Ea(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=Ea(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function Z(r,e,t){it("debug")&&(b(`[${e}][${r}] Messages (${t.length}):`),t.forEach((o,n)=>{b(`[${e}][${r}] #${n} role=${o?.role} content=${A(o?.content,300)}`)}))}function Qr(r,e){if(!e||e.length===0)return;let t=s=>s.function?.name??s.name??"?",o=s=>s.function?.description??s.description??"",n=s=>s.function?.parameters??s.parameters??{};S(`[AIClient][${r}] tools=[${e.map(t).join(", ")}]`),it("debug")&&e.forEach(s=>{b(`[AIClient][${r}] tool=${t(s)} description=${A(o(s),200)} schema=${A(JSON.stringify(n(s)),500)}`)})}var Jr,Vr,st,_=h(()=>{"use strict";l();Jr={error:0,warn:1,info:2,debug:3,trace:4},Vr=class{_enabled=!1;_level="info";_logFile=ew(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=Ra(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=Ra(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=ZT(this._logFile)?this._logFile:tw(process.cwd(),this._logFile),XT(YT(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&&Jr[e]<=Jr[this._level]}getLevel(){return this._level}write(e,t){if(!this.shouldLog(e))return;let o=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${Ea(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)}},st=new Vr});var St={};re(St,{fetchUrlAsBase64:()=>qa,getMimeType:()=>Ia,isDataUri:()=>ja,normalizeImagePart:()=>mw,parseDataUri:()=>La,parseFileEnvelope:()=>at,readFileAsBase64:()=>Fa,toDataUri:()=>pw});import*as Na from"fs/promises";import*as Oa from"path";function Ia(r){let e=Oa.extname(r).toLowerCase();return cw[e]||"application/octet-stream"}function ja(r){return r.startsWith("data:")}function La(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function pw(r,e){return`data:${e};base64,${r}`}async function Fa(r){try{return{data:(await Na.readFile(r)).toString("base64"),mimeType:Ia(r)}}catch(e){throw new N(`Failed to read image file: ${r}`,e)}}async function qa(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 L(`Failed to download image from URL: ${r}`,"FETCH_ERROR",500,e)}}function at(r){if(!r.startsWith("{"))return null;try{let e=JSON.parse(r);if(e?.type==="file"&&typeof e.mimeType=="string"&&typeof e.url=="string")return e}catch{}return null}async function mw(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await Fa(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(ja(e)){let t=La(e);if(!t)throw new N(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await qa(e)}throw new N(`Unknown ImagePart type: ${r.type}`)}var cw,De=h(()=>{"use strict";l();pe();cw={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Kt,Me,pt=h(()=>{"use strict";l();Kt=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)}},Me=new Kt});import*as Qa from"fs/promises";var Jt,Xa,os=h(()=>{"use strict";l();Jt=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 Qa.rm(n.cloneDir,{recursive:!0,force:!0}),this.totalBytes=Math.max(0,this.totalBytes-n.sizeBytes),this.registry.delete(s)}catch{break}}}},Xa=new Jt});import*as Za from"crypto";async function K(r,e,t,o){return(t??kw).resolve(r,e,o)}function Ya(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=Za.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var Vt,kw,xe=h(()=>{"use strict";l();Vt=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=Ya(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=Ya(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}},kw=new Vt});var el={};re(el,{ToolRuntimeContext:()=>ns});var ns,tl=h(()=>{"use strict";l();pt();os();xe();ns=class{processRegistry=new Kt;cloneState=new Jt;githubTokenStore=new Vt}});var ol,nl,rl,sl,il,al=h(()=>{"use strict";l();ol="fs.read_file",nl="Read File",rl="Read the contents of a file at the given path. Returns the file content as a string.",sl="filesystem",il={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 Pt from"fs";async function Sw(r){let e=r.path,t=r.encoding||"utf-8";if(b(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!Pt.existsSync(e))throw new Error(`File not found: ${e}`);if(Pt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return Pt.readFileSync(e,t)}var Qt,rs=h(()=>{"use strict";l();al();_();Qt={name:ol,displayName:nl,description:rl,parameters:il,category:sl,execute:Sw}});var ll,cl,pl,ml,dl,ul=h(()=>{"use strict";l();ll="fs.write_file",cl="Write File",pl="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.",ml="filesystem",dl={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 Rt from"fs";import*as fl from"path";async function _w(r){let e=r.path,t=r.content,o=r.encoding||"utf-8";if(b(`[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=fl.dirname(e);return Rt.existsSync(n)||Rt.mkdirSync(n,{recursive:!0}),Rt.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var Xt,ss=h(()=>{"use strict";l();ul();_();Xt={name:ll,displayName:cl,description:pl,parameters:dl,category:ml,execute:_w,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var gl,hl,yl,bl,Tl,wl=h(()=>{"use strict";l();gl="fs.append_file",hl="Append File",yl="Append content to the end of a file. Creates the file if it does not exist.",bl="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 $t from"fs";import*as xl from"path";async function Pw(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=xl.dirname(e);return $t.existsSync(n)||$t.mkdirSync(n,{recursive:!0}),$t.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Yt,is=h(()=>{"use strict";l();wl();Yt={name:gl,displayName:hl,description:yl,parameters:Tl,category:bl,execute:Pw,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var vl,Cl,kl,Sl,_l,Pl=h(()=>{"use strict";l();vl="fs.delete_file",Cl="Delete File",kl="Remove/delete a file from the filesystem. Does not delete directories.",Sl="filesystem",_l={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as Et from"fs";async function Rw(r){let e=r.path;if(b(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Et.existsSync(e))throw new Error(`File not found: ${e}`);if(Et.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Et.unlinkSync(e),`File deleted successfully: ${e}`}var Zt,as=h(()=>{"use strict";l();Pl();_();Zt={name:vl,displayName:Cl,description:kl,parameters:_l,category:Sl,execute:Rw,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var Rl,$l,El,Dl,Al,Ml=h(()=>{"use strict";l();Rl="fs.exists",$l="Exists",El="Check if a file or directory exists at the given path. Returns true or false.",Dl="filesystem",Al={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as Nl from"fs";async function $w(r){let e=r.path;if(!e)throw new Error("path is required");let t=Nl.existsSync(e);return JSON.stringify({exists:t,path:e})}var eo,ls=h(()=>{"use strict";l();Ml();eo={name:Rl,displayName:$l,description:El,parameters:Al,category:Dl,execute:$w}});var Ol,Il,jl,Ll,Fl,ql=h(()=>{"use strict";l();Ol="fs.stat",Il="Stat",jl="Get file or directory information including size, type, and modification date.",Ll="filesystem",Fl={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as Nn from"fs";async function Ew(r){let e=r.path;if(!e)throw new Error("path is required");if(!Nn.existsSync(e))throw new Error(`Path not found: ${e}`);let t=Nn.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 to,cs=h(()=>{"use strict";l();ql();to={name:Ol,displayName:Il,description:jl,parameters:Fl,category:Ll,execute:Ew}});var Wl,Ul,Gl,Bl,zl,Hl=h(()=>{"use strict";l();Wl="fs.list_dir",Ul="List Directory",Gl="List files and directories at the given path. Optionally recurse into subdirectories.",Bl="filesystem",zl={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 mt from"fs";import*as Kl from"path";function Jl(r,e,t,o=""){let n=mt.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=Kl.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&Jl(i,!0,t,a);else if(s.isFile()){let c=mt.statSync(i);t.push({name:a,type:"file",size:c.size})}}}async function Dw(r){let e=r.path,t=r.recursive===!0;if(!e)throw new Error("path is required");if(!mt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!mt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[];return Jl(e,t,n),JSON.stringify(n,null,2)}var oo,ps=h(()=>{"use strict";l();Hl();oo={name:Wl,displayName:Ul,description:Gl,parameters:zl,category:Bl,execute:Dw}});var Vl,Ql,Xl,Yl,Zl,ec=h(()=>{"use strict";l();Vl="fs.create_dir",Ql="Create Directory",Xl="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Yl="filesystem",Zl={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 Dt from"fs";async function Aw(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(Dt.existsSync(e)){if(Dt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Dt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var no,ms=h(()=>{"use strict";l();ec();no={name:Vl,displayName:Ql,description:Xl,parameters:Zl,category:Yl,execute:Aw}});var tc,oc,nc,rc,sc,ic=h(()=>{"use strict";l();tc="fs.move",oc="Move",nc="Move or rename a file or directory from one path to another.",rc="filesystem",sc={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 dt from"fs";import*as ac from"path";async function Mw(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(!dt.existsSync(e))throw new Error(`Source not found: ${e}`);let o=ac.dirname(t);return dt.existsSync(o)||dt.mkdirSync(o,{recursive:!0}),dt.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var ro,ds=h(()=>{"use strict";l();ic();ro={name:tc,displayName:oc,description:nc,parameters:sc,category:rc,execute:Mw,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var lc,cc,pc,mc,dc,uc=h(()=>{"use strict";l();lc="fs.copy",cc="Copy",pc="Copy a file or directory from one path to another. Recursively copies directories.",mc="filesystem",dc={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 fe from"fs";import*as so from"path";function fc(r,e){if(fe.statSync(r).isDirectory()){fe.existsSync(e)||fe.mkdirSync(e,{recursive:!0});let o=fe.readdirSync(r);for(let n of o)fc(so.join(r,n),so.join(e,n))}else fe.copyFileSync(r,e)}async function Nw(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(!fe.existsSync(e))throw new Error(`Source not found: ${e}`);let o=so.dirname(t);return fe.existsSync(o)||fe.mkdirSync(o,{recursive:!0}),fc(e,t),`Copied ${fe.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var io,us=h(()=>{"use strict";l();uc();io={name:lc,displayName:cc,description:pc,parameters:dc,category:mc,execute:Nw,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var gc,hc,yc,bc,Tc,wc=h(()=>{"use strict";l();gc="fs.read_file_range",hc="Read File Range",yc="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",bc="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 At from"fs";async function Ow(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(!At.existsSync(e))throw new Error(`File not found: ${e}`);if(At.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=At.readFileSync(e,"utf-8").split(`
53
+ `),a=i.length,c=Math.min(t,a),p=Math.min(o,a),m=i.slice(c-1,p).map((g,T)=>`${c+T}: ${g}`).join(`
54
54
  `);return`Lines ${c}-${p} of ${a} total:
55
- ${d}`}var no,cs=h(()=>{"use strict";l();gc();no={name:pc,displayName:mc,description:dc,parameters:fc,category:uc,execute:Ew}});var hc,yc,bc,Tc,wc,xc=h(()=>{"use strict";l();hc="fs.search",yc="Search",bc="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Tc="filesystem",wc={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 vc from"path";function Dw(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 Cc(r,e,t,o,n){let s=We.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=vc.join(r,i.name);i.isDirectory()&&t?Cc(a,e,!0,o,n):i.isFile()&&Dw(a,e,o,n)}}async function Mw(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(Cc(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 ro,ps=h(()=>{"use strict";l();xc();S();ro={name:hc,displayName:yc,description:bc,parameters:wc,category:Tc,execute:Mw}});var kc,Sc,Pc,_c,Rc,$c=h(()=>{"use strict";l();kc="fs.replace_in_file",Sc="Replace In File",Pc="Find and replace text in a file. Returns the number of replacements made.",_c="filesystem",Rc={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 Aw(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 so,ms=h(()=>{"use strict";l();$c();so={name:kc,displayName:Sc,description:Pc,parameters:Rc,category:_c,execute:Aw,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 Ec,Dc,Mc,Ac,Nc,Oc=h(()=>{"use strict";l();Ec="fs.tree",Dc="Tree",Mc="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Ac="filesystem",Nc={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 $t from"fs";import*as Dn from"path";function Ic(r,e,t,o,n){if(t>o)return;let i=$t.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}/`),Ic(Dn.join(r,c.name),e+d,t+1,o,n)):n.push(`${e}${m}${c.name}`)}}async function Nw(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!$t.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!$t.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${Dn.basename(e)}/`];return Ic(e,"",1,t,s),s.join(`
58
- `)}var io,ds=h(()=>{"use strict";l();Oc();io={name:Ec,displayName:Dc,description:Mc,parameters:Nc,category:Ac,execute:Nw}});var jc,Lc,Fc,qc,Wc,Uc=h(()=>{"use strict";l();jc="fs.glob",Lc="Glob Pattern Match",Fc='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',qc="filesystem",Wc={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 Ow from"fast-glob";async function Iw(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 Ow(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 ao,us=h(()=>{"use strict";l();Uc();ao={name:jc,displayName:Lc,description:Fc,parameters:Wc,category:qc,execute:Iw}});var Gc,Bc,zc,Hc,Kc,Jc=h(()=>{"use strict";l();Gc="fs.delete_dir",Bc="Delete Directory",zc="Delete a directory and all its contents recursively",Hc="filesystem",Kc={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 jw}from"fs/promises";import{existsSync as Lw,statSync as Fw}from"fs";async function qw(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!Lw(e))throw new Error(`Directory does not exist: ${e}`);if(!Fw(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await jw(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var lo,fs=h(()=>{"use strict";l();Jc();lo={name:Gc,displayName:Bc,description:zc,parameters:Kc,category:Hc,execute:qw,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var Vc,Qc,Xc,Yc,Zc,ep=h(()=>{"use strict";l();Vc="fs.batch_read",Qc="Batch Read Files",Xc="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",Yc="filesystem",Zc={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 Ww}from"fs/promises";async function Uw(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 Ww(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 co,gs=h(()=>{"use strict";l();ep();co={name:Vc,displayName:Qc,description:Xc,parameters:Zc,category:Yc,execute:Uw}});var tp,op,np,rp,sp,ip=h(()=>{"use strict";l();tp="fs.batch_write",op="Batch Write Files",np="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",rp="filesystem",sp={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 ap,mkdir as Gw,readFile as Bw,unlink as zw}from"fs/promises";import{dirname as Hw,resolve as Kw}from"path";import{existsSync as lp}from"fs";async function Jw(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=Kw(a.path);if(o){let p=lp(c),m={path:c,existed:p};p&&(m.originalContent=await Bw(c,t)),s.push(m)}if(n){let p=Hw(c);await Gw(p,{recursive:!0})}await ap(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 ap(c.path,c.originalContent,t):!c.existed&&lp(c.path)&&await zw(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var po,hs=h(()=>{"use strict";l();ip();po={name:tp,displayName:op,description:np,parameters:sp,category:rp,execute:Jw,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var pp={};te(pp,{fsAppendFileTool:()=>Jt,fsBatchReadTool:()=>co,fsBatchWriteTool:()=>po,fsCopyTool:()=>oo,fsCreateDirTool:()=>Zt,fsDeleteDirTool:()=>lo,fsDeleteFileTool:()=>Vt,fsExistsTool:()=>Qt,fsGlobTool:()=>ao,fsListDirTool:()=>Yt,fsMoveTool:()=>eo,fsReadFileRangeTool:()=>no,fsReadFileTool:()=>Ht,fsReplaceInFileTool:()=>so,fsSearchTool:()=>ro,fsStatTool:()=>Xt,fsToolsProject:()=>cp,fsTreeTool:()=>io,fsWriteFileTool:()=>Kt});var cp,ys=h(()=>{"use strict";l();Zr();es();ts();os();ns();rs();ss();is();as();ls();cs();ps();ms();ds();us();fs();gs();hs();Zr();es();ts();os();ns();rs();ss();is();as();ls();cs();ps();ms();ds();us();fs();gs();hs();cp={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:[Ht,Kt,Jt,Vt,Qt,Xt,Yt,Zt,eo,oo,no,ro,so,io,ao,lo,co,po],dependencies:{"fast-glob":"^3.3.2"}}});var mp,dp,up,fp,gp,hp=h(()=>{"use strict";l();mp="exec.run",dp="Run",up="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",fp="execution",gp={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 Vw}from"child_process";async function Qw(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 Vw(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"}):
55
+ ${m}`}var ao,fs=h(()=>{"use strict";l();wc();ao={name:gc,displayName:hc,description:yc,parameters:Tc,category:bc,execute:Ow}});var xc,vc,Cc,kc,Sc,_c=h(()=>{"use strict";l();xc="fs.search",vc="Search",Cc="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",kc="filesystem",Sc={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 Ke from"fs";import*as Pc from"path";function Iw(r,e,t,o){try{let s=Ke.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 Rc(r,e,t,o,n){let s=Ke.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=Pc.join(r,i.name);i.isDirectory()&&t?Rc(a,e,!0,o,n):i.isFile()&&Iw(a,e,o,n)}}async function jw(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(b(`[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 m=t;s||(m=m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let g=i?"":"i";a=new RegExp(m,g)}if(!Ke.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ke.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(Rc(e,a,o,p,n),p.length===0)return`No matches found for "${t}" in ${e}`;let d=p.length>=n?`
57
+ (results capped at ${n})`:"";return JSON.stringify(p,null,2)+d}var lo,gs=h(()=>{"use strict";l();_c();_();lo={name:xc,displayName:vc,description:Cc,parameters:Sc,category:kc,execute:jw}});var $c,Ec,Dc,Ac,Mc,Nc=h(()=>{"use strict";l();$c="fs.replace_in_file",Ec="Replace In File",Dc="Find and replace text in a file. Returns the number of replacements made.",Ac="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 Je from"fs";async function Lw(r){let e=r.path,t=r.search,o=r.replace;if(!e)throw new Error("path is required");if(!t)throw new Error("search is required");if(o==null)throw new Error("replace is required");if(!Je.existsSync(e))throw new Error(`File not found: ${e}`);if(Je.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let s=Je.readFileSync(e,"utf-8"),i=0,a=0;for(;(a=s.indexOf(t,a))!==-1;)i++,a+=t.length;if(i===0)return`No occurrences of "${t}" found in ${e}`;let c=s.split(t).join(o);return Je.writeFileSync(e,c,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var co,hs=h(()=>{"use strict";l();Nc();co={name:$c,displayName:Ec,description:Dc,parameters:Mc,category:Ac,execute:Lw,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 Oc,Ic,jc,Lc,Fc,qc=h(()=>{"use strict";l();Oc="fs.tree",Ic="Tree",jc="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Lc="filesystem",Fc={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 Mt from"fs";import*as On from"path";function Wc(r,e,t,o,n){if(t>o)return;let i=Mt.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,d=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",m=p?" ":"\u2502 ";c.isDirectory()?(n.push(`${e}${d}${c.name}/`),Wc(On.join(r,c.name),e+m,t+1,o,n)):n.push(`${e}${d}${c.name}`)}}async function Fw(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!Mt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Mt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${On.basename(e)}/`];return Wc(e,"",1,t,s),s.join(`
58
+ `)}var po,ys=h(()=>{"use strict";l();qc();po={name:Oc,displayName:Ic,description:jc,parameters:Fc,category:Lc,execute:Fw}});var Uc,Gc,Bc,zc,Hc,Kc=h(()=>{"use strict";l();Uc="fs.glob",Gc="Glob Pattern Match",Bc='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',zc="filesystem",Hc={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 qw from"fast-glob";async function Ww(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 qw(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 mo,bs=h(()=>{"use strict";l();Kc();mo={name:Uc,displayName:Gc,description:Bc,parameters:Hc,category:zc,execute:Ww}});var Jc,Vc,Qc,Xc,Yc,Zc=h(()=>{"use strict";l();Jc="fs.delete_dir",Vc="Delete Directory",Qc="Delete a directory and all its contents recursively",Xc="filesystem",Yc={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 Uw}from"fs/promises";import{existsSync as Gw,statSync as Bw}from"fs";async function zw(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!Gw(e))throw new Error(`Directory does not exist: ${e}`);if(!Bw(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await Uw(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var uo,Ts=h(()=>{"use strict";l();Zc();uo={name:Jc,displayName:Vc,description:Qc,parameters:Yc,category:Xc,execute:zw,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var ep,tp,op,np,rp,sp=h(()=>{"use strict";l();ep="fs.batch_read",tp="Batch Read Files",op="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",np="filesystem",rp={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 Hw}from"fs/promises";async function Kw(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 Hw(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 fo,ws=h(()=>{"use strict";l();sp();fo={name:ep,displayName:tp,description:op,parameters:rp,category:np,execute:Kw}});var ip,ap,lp,cp,pp,mp=h(()=>{"use strict";l();ip="fs.batch_write",ap="Batch Write Files",lp="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",cp="filesystem",pp={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 dp,mkdir as Jw,readFile as Vw,unlink as Qw}from"fs/promises";import{dirname as Xw,resolve as Yw}from"path";import{existsSync as up}from"fs";async function Zw(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=Yw(a.path);if(o){let p=up(c),d={path:c,existed:p};p&&(d.originalContent=await Vw(c,t)),s.push(d)}if(n){let p=Xw(c);await Jw(p,{recursive:!0})}await dp(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 dp(c.path,c.originalContent,t):!c.existed&&up(c.path)&&await Qw(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var go,xs=h(()=>{"use strict";l();mp();go={name:ip,displayName:ap,description:lp,parameters:pp,category:cp,execute:Zw,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var gp={};re(gp,{fsAppendFileTool:()=>Yt,fsBatchReadTool:()=>fo,fsBatchWriteTool:()=>go,fsCopyTool:()=>io,fsCreateDirTool:()=>no,fsDeleteDirTool:()=>uo,fsDeleteFileTool:()=>Zt,fsExistsTool:()=>eo,fsGlobTool:()=>mo,fsListDirTool:()=>oo,fsMoveTool:()=>ro,fsReadFileRangeTool:()=>ao,fsReadFileTool:()=>Qt,fsReplaceInFileTool:()=>co,fsSearchTool:()=>lo,fsStatTool:()=>to,fsToolsProject:()=>fp,fsTreeTool:()=>po,fsWriteFileTool:()=>Xt});var fp,vs=h(()=>{"use strict";l();rs();ss();is();as();ls();cs();ps();ms();ds();us();fs();gs();hs();ys();bs();Ts();ws();xs();rs();ss();is();as();ls();cs();ps();ms();ds();us();fs();gs();hs();ys();bs();Ts();ws();xs();fp={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:[Qt,Xt,Yt,Zt,eo,to,oo,no,ro,io,ao,lo,co,po,mo,uo,fo,go],dependencies:{"fast-glob":"^3.3.2"}}});var hp,yp,bp,Tp,wp,xp=h(()=>{"use strict";l();hp="exec.run",yp="Run",bp="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Tp="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 ex}from"child_process";async function tx(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");b(`[exec.run] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return ex(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"}):
59
59
  STDOUT:
60
60
  ${s}
61
61
  STDERR:
62
- ${i}`}}var mo,bs=h(()=>{"use strict";l();hp();S();mo={name:mp,displayName:dp,description:up,parameters:gp,category:fp,execute:Qw,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var yp,bp,Tp,wp,xp,vp=h(()=>{"use strict";l();yp="exec.run_shell",bp="Run Shell",Tp="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",wp="execution",xp={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 Xw}from"child_process";function Yw(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function Zw(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 Xw(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Yw()})||"(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 ho,Cs=h(()=>{"use strict";l();xp();_();ho={name:hp,displayName:yp,description:bp,parameters:wp,category:Tp,execute:tx,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var vp,Cp,kp,Sp,_p,Pp=h(()=>{"use strict";l();vp="exec.run_shell",Cp="Run Shell",kp="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",Sp="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 ox}from"child_process";function nx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function rx(r){let e=r.command,t=r.cwd,o=r.timeout||3e4;if(!e)throw new Error("command is required");b(`[exec.run-shell] execute command="${e.substring(0,100)}" cwd=${t??"default"} timeout=${o}ms`);try{return ox(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:nx()})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
63
63
  STDOUT:
64
64
  ${s}
65
65
  STDERR:
66
- ${i}`}}var uo,Ts=h(()=>{"use strict";l();vp();S();uo={name:yp,displayName:bp,description:Tp,parameters:xp,category:wp,execute:Zw,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});var Cp,kp,Sp,Pp,_p,Rp=h(()=>{"use strict";l();Cp="exec.run_background",kp="Run Background",Sp="Start a command as a background process. Returns a process ID that can be used with exec.read_output, exec.kill, and exec.list_processes.",Pp="execution",_p={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 ex}from"child_process";async function tx(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=ex(t,[],{cwd:o,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),i=(e?.processRegistry??Re).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 fo,ws=h(()=>{"use strict";l();nt();Rp();S();fo={name:Cp,displayName:kp,description:Sp,parameters:_p,category:Pp,execute:tx,confirmation:{level:"medium",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var $p,Ep,Dp,Mp,Ap,Np=h(()=>{"use strict";l();$p="exec.run_blocking",Ep="Run Blocking",Dp="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.",Mp="execution",Ap={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 ox}from"child_process";function nx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function rx(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=ox(e,[],{cwd:t,shell:nx(),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 go,xs=h(()=>{"use strict";l();Np();S();go={name:$p,displayName:Ep,description:Dp,parameters:Ap,category:Mp,execute:rx,confirmation:{level:"medium",reason:"This will execute a shell command and block until it completes.",showArgs:["command"]}}});var Op,Ip,jp,Lp,Fp,qp=h(()=>{"use strict";l();Op="exec.read_output",Ip="Read Output",jp="Read stdout and stderr from a background process started with exec.run_background.",Lp="execution",Fp={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function sx(r,e){let t=r.process_id;if(!t)throw new Error("process_id is required");let n=(e?.processRegistry??Re).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 ho,vs=h(()=>{"use strict";l();nt();qp();ho={name:Op,displayName:Ip,description:jp,parameters:Fp,category:Lp,execute:sx}});var Wp,Up,Gp,Bp,zp,Hp=h(()=>{"use strict";l();Wp="exec.tail_output",Up="Tail Process Output",Gp="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.",Bp="execution",zp={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 ix(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??Re).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(`
66
+ ${i}`}}var yo,ks=h(()=>{"use strict";l();Pp();_();yo={name:vp,displayName:Cp,description:kp,parameters:_p,category:Sp,execute:rx,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});var Rp,$p,Ep,Dp,Ap,Mp=h(()=>{"use strict";l();Rp="exec.run_background",$p="Run Background",Ep="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.",Dp="execution",Ap={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 sx}from"child_process";async function ix(r,e){let t=r.command,o=r.cwd;if(!t)throw new Error("command is required");b(`[exec.run-background] execute command="${t.substring(0,100)}" cwd=${o??"default"}`);let n=sx(t,[],{cwd:o,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),i=(e?.processRegistry??Me).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 bo,Ss=h(()=>{"use strict";l();pt();Mp();_();bo={name:Rp,displayName:$p,description:Ep,parameters:Ap,category:Dp,execute:ix,confirmation:{level:"medium",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var Np,Op,Ip,jp,Lp,Fp=h(()=>{"use strict";l();Np="exec.run_blocking",Op="Run Blocking",Ip="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.",jp="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 ax}from"child_process";function lx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function cx(r){let e=r.command,t=r.cwd;if(!e)throw new Error("command is required");return b(`[exec.run-blocking] execute command="${e.substring(0,100)}" cwd=${t??"default"} (no timeout)`),new Promise(o=>{let n="",s="",i=ax(e,[],{cwd:t,shell:lx(),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;b(`[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=>{b(`[exec.run-blocking] spawn error: ${a.message}`),o(JSON.stringify({exitCode:1,stdout:"",stderr:a.message,success:!1}))})})}var To,_s=h(()=>{"use strict";l();Fp();_();To={name:Np,displayName:Op,description:Ip,parameters:Lp,category:jp,execute:cx,confirmation:{level:"medium",reason:"This will execute a shell command and block until it completes.",showArgs:["command"]}}});var qp,Wp,Up,Gp,Bp,zp=h(()=>{"use strict";l();qp="exec.read_output",Wp="Read Output",Up="Read stdout and stderr from a background process started with exec.run_background.",Gp="execution",Bp={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function px(r,e){let t=r.process_id;if(!t)throw new Error("process_id is required");let n=(e?.processRegistry??Me).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,Ps=h(()=>{"use strict";l();pt();zp();wo={name:qp,displayName:Wp,description:Up,parameters:Bp,category:Gp,execute:px}});var Hp,Kp,Jp,Vp,Qp,Xp=h(()=>{"use strict";l();Hp="exec.tail_output",Kp="Tail Process Output",Jp="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.",Vp="execution",Qp={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 mx(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??Me).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
67
  `),p=c.slice(-o).join(`
68
- `).trim(),d=s.stderr.split(`
68
+ `).trim(),m=s.stderr.split(`
69
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 yo,Cs=h(()=>{"use strict";l();nt();Hp();yo={name:Wp,displayName:Up,description:Gp,parameters:zp,category:Bp,execute:ix}});var Kp,Jp,Vp,Qp,Xp,Yp=h(()=>{"use strict";l();Kp="exec.kill",Jp="Kill",Vp="Kill a background process started with exec.run_background.",Qp="execution",Xp={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function ax(r,e){let t=r.process_id;if(!t)throw new Error("process_id is required");let o=e?.processRegistry??Re,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 bo,ks=h(()=>{"use strict";l();nt();Yp();bo={name:Kp,displayName:Jp,description:Vp,parameters:Xp,category:Qp,execute:ax,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var Zp,em,tm,om,nm,rm=h(()=>{"use strict";l();Zp="exec.list_processes",em="List Processes",tm="List all managed background processes started with exec.run_background, including their status.",om="execution",nm={type:"object",properties:{}}});async function lx(r,e){let o=(e?.processRegistry??Re).list();return o.length===0?"No managed background processes.":JSON.stringify(o,null,2)}var To,Ss=h(()=>{"use strict";l();nt();rm();To={name:Zp,displayName:em,description:tm,parameters:nm,category:om,execute:lx}});var im={};te(im,{execKillTool:()=>bo,execListProcessesTool:()=>To,execReadOutputTool:()=>ho,execRunBackgroundTool:()=>fo,execRunBlockingTool:()=>go,execRunShellTool:()=>uo,execRunTool:()=>mo,execTailOutputTool:()=>yo,execToolsProject:()=>sm});var sm,Ps=h(()=>{"use strict";l();bs();Ts();ws();xs();vs();Cs();ks();Ss();bs();Ts();ws();xs();vs();Cs();ks();Ss();sm={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:[mo,uo,fo,go,ho,yo,bo,To],dependencies:{}}});var am,lm,cm,pm,mm,dm=h(()=>{"use strict";l();am="system.info",lm="Info",cm="Get system information including OS, CPU, memory, and architecture.",pm="system",mm={type:"object",properties:{}}});import*as j from"os";async function cx(r){return y("[system.info] execute"),JSON.stringify({platform:j.platform(),arch:j.arch(),release:j.release(),hostname:j.hostname(),uptime:j.uptime(),cpus:{model:j.cpus()[0]?.model||"unknown",count:j.cpus().length},memory:{total:j.totalmem(),free:j.freemem(),used:j.totalmem()-j.freemem()},homedir:j.homedir(),tmpdir:j.tmpdir(),nodeVersion:process.version},null,2)}var wo,_s=h(()=>{"use strict";l();dm();S();wo={name:am,displayName:lm,description:cm,parameters:mm,category:pm,execute:cx}});var um,fm,gm,hm,ym,bm=h(()=>{"use strict";l();um="system.env",fm="Environment",gm="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",hm="system",ym={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function px(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 xo,Rs=h(()=>{"use strict";l();bm();S();xo={name:um,displayName:fm,description:gm,parameters:ym,category:hm,execute:px}});var Tm,wm,xm,vm,Cm,km=h(()=>{"use strict";l();Tm="system.set_env",wm="Set Environment",xm="Set an environment variable for the current session. Does not persist across restarts.",vm="system",Cm={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function mx(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 vo,$s=h(()=>{"use strict";l();km();vo={name:Tm,displayName:wm,description:xm,parameters:Cm,category:vm,execute:mx,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var Sm,Pm,_m,Rm,$m,Em=h(()=>{"use strict";l();Sm="system.cwd",Pm="Current Directory",_m="Get the current working directory of the process.",Rm="system",$m={type:"object",properties:{}}});async function dx(r){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var Co,Es=h(()=>{"use strict";l();Em();S();Co={name:Sm,displayName:Pm,description:_m,parameters:$m,category:Rm,execute:dx}});var Dm,Mm,Am,Nm,Om,Im=h(()=>{"use strict";l();Dm="system.disk_usage",Mm="Disk Usage",Am="Get disk usage information for a given path or the root filesystem.",Nm="system",Om={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});import*as Lm from"fs";import*as Fm from"os";import*as Mn from"path";import{execSync as jm}from"child_process";function Ds(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 ux(r){let t=r.path||(process.platform==="win32"?Fm.tmpdir():"/");t=Mn.resolve(t);let o=process.platform==="win32";try{let n=Lm.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:Ds(Number(s)),used:Ds(Number(c)),available:Ds(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(n){try{if(o){let c=Mn.parse(t).root.replace(/\\$/,"")||"C:",p=`Get-PSDrive -Name ${c.replace(":","")} | Select-Object @{n='Drive';e={$_.Name+':'}},@{n='Used';e={$_.Used}},@{n='Free';e={$_.Free}},@{n='Total';e={$_.Used+$_.Free}} | ConvertTo-Json`,m=jm(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),d=JSON.parse(m.trim()),g=d.Total||0,T=d.Free||0,b=d.Used||0,w=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:`${(T/1024**3).toFixed(1)}G`,usePercent:`${w}%`,mountedOn:d.Drive||`${c}`},null,2)}let s=jm(`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 ko,Ms=h(()=>{"use strict";l();Im();ko={name:Dm,displayName:Mm,description:Am,parameters:Om,category:Nm,execute:ux}});var Wm={};te(Wm,{systemCwdTool:()=>Co,systemDiskUsageTool:()=>ko,systemEnvTool:()=>xo,systemInfoTool:()=>wo,systemSetEnvTool:()=>vo,systemToolsProject:()=>qm});var qm,As=h(()=>{"use strict";l();_s();Rs();$s();Es();Ms();_s();Rs();$s();Es();Ms();qm={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:[wo,xo,vo,Co,ko],dependencies:{}}});var Um,Gm,Bm,zm,Hm,Km=h(()=>{"use strict";l();Um="http.get",Gm="GET",Bm="Make an HTTP GET request to a URL and return the response body.",zm="http",Hm={type:"object",properties:{url:{type:"string",description:"The URL to request"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function fx(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>Jm?`${s}
72
- ${n.substring(0,Jm)}
70
+ `).trim();return JSON.stringify({id:t,alive:i,exitCode:a,lastLines:p||"(no output yet)",lastStderr:m||"",totalStdoutLines:c.length})}var xo,Rs=h(()=>{"use strict";l();pt();Xp();xo={name:Hp,displayName:Kp,description:Jp,parameters:Qp,category:Vp,execute:mx}});var Yp,Zp,em,tm,om,nm=h(()=>{"use strict";l();Yp="exec.kill",Zp="Kill",em="Kill a background process started with exec.run_background.",tm="execution",om={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function dx(r,e){let t=r.process_id;if(!t)throw new Error("process_id is required");let o=e?.processRegistry??Me,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 vo,$s=h(()=>{"use strict";l();pt();nm();vo={name:Yp,displayName:Zp,description:em,parameters:om,category:tm,execute:dx,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var rm,sm,im,am,lm,cm=h(()=>{"use strict";l();rm="exec.list_processes",sm="List Processes",im="List all managed background processes started with exec.run_background, including their status.",am="execution",lm={type:"object",properties:{}}});async function ux(r,e){let o=(e?.processRegistry??Me).list();return o.length===0?"No managed background processes.":JSON.stringify(o,null,2)}var Co,Es=h(()=>{"use strict";l();pt();cm();Co={name:rm,displayName:sm,description:im,parameters:lm,category:am,execute:ux}});var mm={};re(mm,{execKillTool:()=>vo,execListProcessesTool:()=>Co,execReadOutputTool:()=>wo,execRunBackgroundTool:()=>bo,execRunBlockingTool:()=>To,execRunShellTool:()=>yo,execRunTool:()=>ho,execTailOutputTool:()=>xo,execToolsProject:()=>pm});var pm,Ds=h(()=>{"use strict";l();Cs();ks();Ss();_s();Ps();Rs();$s();Es();Cs();ks();Ss();_s();Ps();Rs();$s();Es();pm={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:[ho,yo,bo,To,wo,xo,vo,Co],dependencies:{}}});var dm,um,fm,gm,hm,ym=h(()=>{"use strict";l();dm="system.info",um="Info",fm="Get system information including OS, CPU, memory, and architecture.",gm="system",hm={type:"object",properties:{}}});import*as q from"os";async function fx(r){return b("[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 ko,As=h(()=>{"use strict";l();ym();_();ko={name:dm,displayName:um,description:fm,parameters:hm,category:gm,execute:fx}});var bm,Tm,wm,xm,vm,Cm=h(()=>{"use strict";l();bm="system.env",Tm="Environment",wm="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",xm="system",vm={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function gx(r){let e=r.key;if(b(`[system.env] execute key=${e??"all"}`),e){let n=process.env[e];return n===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:n})}let t={},o=Object.keys(process.env).sort();for(let n of o)process.env[n]!==void 0&&(t[n]=process.env[n]);return JSON.stringify(t,null,2)}var So,Ms=h(()=>{"use strict";l();Cm();_();So={name:bm,displayName:Tm,description:wm,parameters:vm,category:xm,execute:gx}});var km,Sm,_m,Pm,Rm,$m=h(()=>{"use strict";l();km="system.set_env",Sm="Set Environment",_m="Set an environment variable for the current session. Does not persist across restarts.",Pm="system",Rm={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function hx(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 _o,Ns=h(()=>{"use strict";l();$m();_o={name:km,displayName:Sm,description:_m,parameters:Rm,category:Pm,execute:hx,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var Em,Dm,Am,Mm,Nm,Om=h(()=>{"use strict";l();Em="system.cwd",Dm="Current Directory",Am="Get the current working directory of the process.",Mm="system",Nm={type:"object",properties:{}}});async function yx(r){return b("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var Po,Os=h(()=>{"use strict";l();Om();_();Po={name:Em,displayName:Dm,description:Am,parameters:Nm,category:Mm,execute:yx}});var Im,jm,Lm,Fm,qm,Wm=h(()=>{"use strict";l();Im="system.disk_usage",jm="Disk Usage",Lm="Get disk usage information for a given path or the root filesystem.",Fm="system",qm={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});import*as Gm from"fs";import*as Bm from"os";import*as In from"path";import{execSync as Um}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 bx(r){let t=r.path||(process.platform==="win32"?Bm.tmpdir():"/");t=In.resolve(t);let o=process.platform==="win32";try{let n=Gm.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=In.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`,d=Um(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),m=JSON.parse(d.trim()),g=m.Total||0,T=m.Free||0,y=m.Used||0,w=g>0?Math.round(y/g*100):0;return JSON.stringify({path:t,filesystem:m.Name||"NTFS",size:`${(g/1024**3).toFixed(1)}G`,used:`${(y/1024**3).toFixed(1)}G`,available:`${(T/1024**3).toFixed(1)}G`,usePercent:`${w}%`,mountedOn:m.Drive||`${c}`},null,2)}let s=Um(`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 Ro,js=h(()=>{"use strict";l();Wm();Ro={name:Im,displayName:jm,description:Lm,parameters:qm,category:Fm,execute:bx}});var Hm={};re(Hm,{systemCwdTool:()=>Po,systemDiskUsageTool:()=>Ro,systemEnvTool:()=>So,systemInfoTool:()=>ko,systemSetEnvTool:()=>_o,systemToolsProject:()=>zm});var zm,Ls=h(()=>{"use strict";l();As();Ms();Ns();Os();js();As();Ms();Ns();Os();js();zm={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:[ko,So,_o,Po,Ro],dependencies:{}}});var Km,Jm,Vm,Qm,Xm,Ym=h(()=>{"use strict";l();Km="http.get",Jm="GET",Vm="Make an HTTP GET request to a URL and return the response body.",Qm="http",Xm={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(b(`[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>Zm?`${s}
72
+ ${n.substring(0,Zm)}
73
73
 
74
74
  ... (truncated, total ${n.length} characters)`:`${s}
75
75
  ${n}`:`${s}
76
- ${n}`}var Jm,So,Ns=h(()=>{"use strict";l();Km();S();Jm=1e5;So={name:Um,displayName:Gm,description:Bm,parameters:Hm,category:zm,execute:fx}});var Vm,Qm,Xm,Ym,Zm,ed=h(()=>{"use strict";l();Vm="http.post",Qm="POST",Xm="Make an HTTP POST request to a URL with an optional body and return the response.",Ym="http",Zm={type:"object",properties:{url:{type:"string",description:"The URL to request"},body:{type:"string",description:"Request body (JSON string or plain text)"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function gx(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>td?`${i}
77
- ${s.substring(0,td)}
76
+ ${n}`}var Zm,$o,Fs=h(()=>{"use strict";l();Ym();_();Zm=1e5;$o={name:Km,displayName:Jm,description:Vm,parameters:Xm,category:Qm,execute:Tx}});var ed,td,od,nd,rd,sd=h(()=>{"use strict";l();ed="http.post",td="POST",od="Make an HTTP POST request to a URL with an optional body and return the response.",nd="http",rd={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 wx(r){let e=r.url,t=r.body,o=r.headers||{};if(b(`[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>id?`${i}
77
+ ${s.substring(0,id)}
78
78
 
79
79
  ... (truncated, total ${s.length} characters)`:`${i}
80
- ${s}`}var td,Po,Os=h(()=>{"use strict";l();ed();S();td=1e5;Po={name:Vm,displayName:Qm,description:Xm,parameters:Zm,category:Ym,execute:gx,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var od,nd,rd,sd,id,ad=h(()=>{"use strict";l();od="http.put",nd="PUT",rd="Make an HTTP PUT request to a URL with an optional body and return the response.",sd="http",id={type:"object",properties:{url:{type:"string",description:"The URL to request"},body:{type:"string",description:"Request body (JSON string or plain text)"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function hx(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>ld?`${i}
81
- ${s.substring(0,ld)}
80
+ ${s}`}var id,Eo,qs=h(()=>{"use strict";l();sd();_();id=1e5;Eo={name:ed,displayName:td,description:od,parameters:rd,category:nd,execute:wx,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var ad,ld,cd,pd,md,dd=h(()=>{"use strict";l();ad="http.put",ld="PUT",cd="Make an HTTP PUT request to a URL with an optional body and return the response.",pd="http",md={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(b(`[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>ud?`${i}
81
+ ${s.substring(0,ud)}
82
82
 
83
83
  ... (truncated)`:`${i}
84
- ${s}`}var ld,_o,Is=h(()=>{"use strict";l();ad();S();ld=1e5;_o={name:od,displayName:nd,description:rd,parameters:id,category:sd,execute:hx,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var cd,pd,md,dd,ud,fd=h(()=>{"use strict";l();cd="http.delete",pd="DELETE",md="Make an HTTP DELETE request to a URL and return the response.",dd="http",ud={type:"object",properties:{url:{type:"string",description:"The URL to request"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function yx(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>gd?`${s}
85
- ${n.substring(0,gd)}
84
+ ${s}`}var ud,Do,Ws=h(()=>{"use strict";l();dd();_();ud=1e5;Do={name:ad,displayName:ld,description:cd,parameters:md,category:pd,execute:xx,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var fd,gd,hd,yd,bd,Td=h(()=>{"use strict";l();fd="http.delete",gd="DELETE",hd="Make an HTTP DELETE request to a URL and return the response.",yd="http",bd={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 vx(r){let e=r.url,t=r.headers;if(b(`[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)}
86
86
 
87
87
  ... (truncated)`:`${s}
88
- ${n}`}var gd,Ro,js=h(()=>{"use strict";l();fd();S();gd=1e5;Ro={name:cd,displayName:pd,description:md,parameters:ud,category:dd,execute:yx,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var hd,yd,bd,Td,wd,xd=h(()=>{"use strict";l();hd="http.download",yd="Download",bd="Download a file from a URL and save it to a local path.",Td="http",wd={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});import*as Et from"fs";import*as vd from"path";async function bx(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=vd.dirname(t);return Et.existsSync(i)||Et.mkdirSync(i,{recursive:!0}),Et.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var $o,Ls=h(()=>{"use strict";l();xd();S();$o={name:hd,displayName:yd,description:bd,parameters:wd,category:Td,execute:bx}});var kd={};te(kd,{httpDeleteTool:()=>Ro,httpDownloadTool:()=>$o,httpGetTool:()=>So,httpPostTool:()=>Po,httpPutTool:()=>_o,httpToolsProject:()=>Cd});var Cd,Fs=h(()=>{"use strict";l();Ns();Os();Is();js();Ls();Ns();Os();Is();js();Ls();Cd={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:"http"},tools:[So,Po,_o,Ro,$o],dependencies:{}}});var Sd,Pd,_d,Rd,$d,Ed=h(()=>{"use strict";l();Sd="github.graphql.execute",Pd="GitHub GraphQL",_d=["Execute a GitHub GraphQL query or mutation with standard headers.","NOTE: GitHub App installation tokens (ghs_*) cannot call certain write mutations.","The following mutations require a PAT and will return FORBIDDEN with an App token:","resolveReviewThread, unresolveReviewThread.","If using an App token, avoid these mutations and use fallback strategies (replies, new comments)."].join(" "),Rd="github",$d={type:"object",properties:{query:{type:"string",description:"GraphQL query string"},variables:{type:"object",description:"Optional GraphQL variables"},repo:{type:"string",description:"owner/name \u2014 used for token resolution when no explicit token is provided"},token:{type:"string",description:"GitHub token (App installation or PAT). Optional \u2014 omit to auto-resolve from server credentials."}},required:["query"]}});function J(r,e){let t={Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...e||{}};return r&&(t.Authorization=`Bearer ${r}`),t}var $e=h(()=>{"use strict";l()});async function Tx(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:J(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 Eo,qs=h(()=>{"use strict";l();Ed();S();$e();ye();Eo={name:Sd,displayName:Pd,description:_d,parameters:$d,category:Rd,execute:Tx}});var Dd,Md,Ad,Nd,Od,Id=h(()=>{"use strict";l();Dd="github.contents.getText",Md="Get Repo File (Text)",Ad="Fetch file content (decoded text) via the GitHub Contents API.",Nd="github",Od={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 An}from"buffer";async function wx(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:J(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 T=An.from(g.replace(/\n/g,""),"base64").toString("utf8");if(i&&An.byteLength(T,"utf8")>i){let b=An.from(T,"utf8").subarray(0,i).toString("utf8"),w=`
91
- \u2026 [truncated, ${i} of ${An.byteLength(T,"utf8")} bytes]`;return`HTTP ${p.status} ${p.statusText}
92
- ${b}${w}`}return`HTTP ${p.status} ${p.statusText}
88
+ ${n}`}var wd,Ao,Us=h(()=>{"use strict";l();Td();_();wd=1e5;Ao={name:fd,displayName:gd,description:hd,parameters:bd,category:yd,execute:vx,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var xd,vd,Cd,kd,Sd,_d=h(()=>{"use strict";l();xd="http.download",vd="Download",Cd="Download a file from a URL and save it to a local path.",kd="http",Sd={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 Nt from"fs";import*as Pd from"path";async function Cx(r){let e=r.url,t=r.path,o=r.headers;if(b(`[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 Nt.existsSync(i)||Nt.mkdirSync(i,{recursive:!0}),Nt.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var Mo,Gs=h(()=>{"use strict";l();_d();_();Mo={name:xd,displayName:vd,description:Cd,parameters:Sd,category:kd,execute:Cx}});var $d={};re($d,{httpDeleteTool:()=>Ao,httpDownloadTool:()=>Mo,httpGetTool:()=>$o,httpPostTool:()=>Eo,httpPutTool:()=>Do,httpToolsProject:()=>Rd});var Rd,Bs=h(()=>{"use strict";l();Fs();qs();Ws();Us();Gs();Fs();qs();Ws();Us();Gs();Rd={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:"http"},tools:[$o,Eo,Do,Ao,Mo],dependencies:{}}});var Ed,Dd,Ad,Md,Nd,Od=h(()=>{"use strict";l();Ed="github.graphql.execute",Dd="GitHub GraphQL",Ad=["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",Nd={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 Q(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 Ne=h(()=>{"use strict";l()});async function kx(r,e){let t=r.query,o=r.variables??{},n=await K(r.repo,r.token,e?.githubTokenStore,e?.config?.credentials);b(`[github.graphql.execute] query_len=${t?.length??0}`);let s=await fetch("https://api.github.com/graphql",{method:"POST",headers:Q(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&&b(`[github.graphql.execute] errors=${a.errors.length}`)}catch{}return`HTTP ${s.status} ${s.statusText}
89
+ ${i}`}var No,zs=h(()=>{"use strict";l();Od();_();Ne();xe();No={name:Ed,displayName:Dd,description:Ad,parameters:Nd,category:Md,execute:kx}});var Id,jd,Ld,Fd,qd,Wd=h(()=>{"use strict";l();Id="github.contents.getText",jd="Get Repo File (Text)",Ld="Fetch file content (decoded text) via the GitHub Contents API.",Fd="github",qd={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 jn}from"buffer";async function Sx(r,e){let t=r.repo,o=r.path,n=r.ref,s=await K(t,r.token,e?.githubTokenStore,e?.config?.credentials),i=r.maxBytes?Number(r.maxBytes):void 0,a=o.split("/").map(m=>encodeURIComponent(m)).join("/"),c=`https://api.github.com/repos/${t}/contents/${a}${n?`?ref=${encodeURIComponent(n)}`:""}`;b(`[github.contents.getText] repo=${t} path=${o} ref=${n??""}`);let p=await fetch(c,{method:"GET",headers:Q(s)}),d=await p.text();if(!p.ok)return`HTTP ${p.status} ${p.statusText}
90
+ ${d}`;try{let g=JSON.parse(d)?.content;if(typeof g=="string"){let T=jn.from(g.replace(/\n/g,""),"base64").toString("utf8");if(i&&jn.byteLength(T,"utf8")>i){let y=jn.from(T,"utf8").subarray(0,i).toString("utf8"),w=`
91
+ \u2026 [truncated, ${i} of ${jn.byteLength(T,"utf8")} bytes]`;return`HTTP ${p.status} ${p.statusText}
92
+ ${y}${w}`}return`HTTP ${p.status} ${p.statusText}
93
93
  ${T}`}}catch{}return`HTTP ${p.status} ${p.statusText}
94
- ${m}`}var Do,Ws=h(()=>{"use strict";l();Id();S();$e();ye();Do={name:Dd,displayName:Md,description:Ad,parameters:Od,category:Nd,execute:wx}});var jd,Ld,Fd,qd,Wd,Ud=h(()=>{"use strict";l();jd="github.pr.reviewThreads.list",Ld="List PR Review Threads",Fd="List PR review threads via GraphQL (optionally unresolved only).",qd="github",Wd={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},unresolvedOnly:{type:"boolean",description:"If true, filter unresolved threads only"},first:{type:"integer",description:"Threads page size (max 100). Default 100."},after:{type:"string",description:"Cursor for pagination (GraphQL pageInfo.endCursor)."},commentsFirst:{type:"integer",description:"Comments per thread (max 100). Default 20."},includeMeta:{type:"boolean",description:"If true, return { headRefOid, threads, pageInfo } instead of array."}},required:["repo","number"]}});async function xx(r,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:J(s,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
94
+ ${d}`}var Oo,Hs=h(()=>{"use strict";l();Wd();_();Ne();xe();Oo={name:Id,displayName:jd,description:Ld,parameters:qd,category:Fd,execute:Sx}});var Ud,Gd,Bd,zd,Hd,Kd=h(()=>{"use strict";l();Ud="github.pr.reviewThreads.list",Gd="List PR Review Threads",Bd="List PR review threads via GraphQL (optionally unresolved only).",zd="github",Hd={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 K(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,d=!!r.includeMeta;b(`[github.pr.reviewThreads.list] repo=${t}/${o} pr=${n} unresolvedOnly=${i} first=${a} after=${c??""} commentsFirst=${p} includeMeta=${d}`);let g=await fetch("https://api.github.com/graphql",{method:"POST",headers:Q(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
@@ -102,28 +102,28 @@ ${m}`}var Do,Ws=h(()=>{"use strict";l();Id();S();$e();ye();Do={name:Dd,displayNa
102
102
  }
103
103
  }
104
104
  }`,variables:{owner:t,name:o,number:n,first:a,after:c,commentsFirst:p}})}),T=await g.text();if(!g.ok)return`HTTP ${g.status} ${g.statusText}
105
- ${T}`;try{let b=JSON.parse(T);b&&Array.isArray(b.errors)&&b.errors.length>0&&y(`[github.pr.reviewThreads.list] errors=${b.errors.length}`);let w=b?.data?.repository?.pullRequest,k=w?.reviewThreads?.pageInfo??{hasNextPage:!1,endCursor:null},v=w?.reviewThreads?.nodes??[];if(i&&(v=v.filter(x=>x?.isResolved===!1)),m){let x={headRefOid:w?.headRefOid,threads:v,pageInfo:k};return`HTTP 200 OK
105
+ ${T}`;try{let y=JSON.parse(T);y&&Array.isArray(y.errors)&&y.errors.length>0&&b(`[github.pr.reviewThreads.list] errors=${y.errors.length}`);let w=y?.data?.repository?.pullRequest,k=w?.reviewThreads?.pageInfo??{hasNextPage:!1,endCursor:null},C=w?.reviewThreads?.nodes??[];if(i&&(C=C.filter(x=>x?.isResolved===!1)),d){let x={headRefOid:w?.headRefOid,threads:C,pageInfo:k};return`HTTP 200 OK
106
106
  ${JSON.stringify(x)}`}return`HTTP 200 OK
107
- ${JSON.stringify(v)}`}catch{return`HTTP ${g.status} ${g.statusText}
108
- ${T}`}}var Mo,Us=h(()=>{"use strict";l();Ud();$e();S();ye();Mo={name:jd,displayName:Ld,description:Fd,parameters:Wd,category:qd,execute:xx}});var Gd,Bd,zd,Hd,Kd,Jd=h(()=>{"use strict";l();Gd="github.pr.reviewThreads.resolve",Bd="Resolve Review Thread",zd=["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(" "),Hd="github",Kd={type:"object",properties:{threadId:{type:"string",description:"GraphQL node ID of the review thread"},repo:{type:"string",description:"owner/name \u2014 used for token resolution when no explicit token is provided"},token:{type:"string",description:"GitHub token \u2014 MUST be a PAT with repo scope. App installation tokens (ghs_*) will receive FORBIDDEN."}},required:["threadId"]}});async function vx(r,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:J(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 Ao,Gs=h(()=>{"use strict";l();Jd();$e();S();ye();Ao={name:Gd,displayName:Bd,description:zd,parameters:Kd,category:Hd,execute:vx}});var Vd,Qd,Xd,Yd,Zd,eu=h(()=>{"use strict";l();Vd="github.pr.reviewComments.reply",Qd="Reply to Review Comment",Xd="Reply within an existing PR review thread to maintain continuity.",Yd="github",Zd={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},inReplyTo:{type:"integer",description:"databaseId of the review comment to reply to"},body:{type:"string",description:"Reply body"},token:{type:"string",description:"GitHub token (App installation or PAT)"}},required:["repo","number","inReplyTo","body"]}});async function Cx(r,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:J(i,{"Content-Type":"application/json"}),body:JSON.stringify({body:s})}),p=await c.text();return`HTTP ${c.status} ${c.statusText}
110
- ${p}`}var No,Bs=h(()=>{"use strict";l();eu();S();$e();ye();No={name:Vd,displayName:Qd,description:Xd,parameters:Zd,category:Yd,execute:Cx}});var tu,ou,nu,ru,su,iu=h(()=>{"use strict";l();tu="github.pr.diff.get",ou="Get PR Diff",nu="Fetch the unified diff for a pull request (text/patch).",ru="github",su={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},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 zs}from"buffer";async function kx(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:J(n,{Accept:"application/vnd.github.v3.diff"})}),c=await a.text();if(s&&zs.byteLength(c,"utf8")>s){let p=zs.from(c,"utf8").subarray(0,s).toString("utf8"),m=`
111
- \u2026 [truncated, ${s} of ${zs.byteLength(c,"utf8")} bytes]`;return`HTTP ${a.status} ${a.statusText}
112
- ${p}${m}`}return`HTTP ${a.status} ${a.statusText}
113
- ${c}`}var Oo,Hs=h(()=>{"use strict";l();iu();$e();S();ye();Oo={name:tu,displayName:ou,description:nu,parameters:su,category:ru,execute:kx}});var au,lu,cu,pu,mu,du=h(()=>{"use strict";l();au="github.pr.files.list",lu="List PR Files",cu="List files changed in a PR with positions metadata.",pu="github",mu={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 Sx(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:J(n)}),m=await p.text();return`HTTP ${p.status} ${p.statusText}
114
- ${m}`}var Io,Ks=h(()=>{"use strict";l();du();$e();S();ye();Io={name:au,displayName:lu,description:cu,parameters:mu,category:pu,execute:Sx}});var uu,fu,gu,hu,yu,bu=h(()=>{"use strict";l();uu="github.pr.reviews.submit",fu="Submit PR Review",gu="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",hu="github",yu={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 Px(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:J(a,{"Content-Type":"application/json"}),body:JSON.stringify(p)}),d=await m.text();return`HTTP ${m.status} ${m.statusText}
115
- ${d}`}var jo,Js=h(()=>{"use strict";l();bu();$e();S();ye();jo={name:uu,displayName:fu,description:gu,parameters:yu,category:hu,execute:Px}});var Tu,wu,xu,vu,Cu,ku=h(()=>{"use strict";l();Tu="github.issues.comments.create",wu="Create Issue/PR Comment",xu="Create a comment on an issue or pull request (conversation tab).",vu="github",Cu={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 _x(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:J(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),c=await a.text();return`HTTP ${a.status} ${a.statusText}
116
- ${c}`}var Lo,Vs=h(()=>{"use strict";l();ku();$e();S();ye();Lo={name:Tu,displayName:wu,description:xu,parameters:Cu,category:vu,execute:_x}});var Pu={};te(Pu,{githubContentsGetTextTool:()=>Do,githubGraphqlExecuteTool:()=>Eo,githubIssuesCommentsCreateTool:()=>Lo,githubPrDiffGetTool:()=>Oo,githubPrFilesListTool:()=>Io,githubPrReviewCommentsReplyTool:()=>No,githubPrReviewThreadsListTool:()=>Mo,githubPrReviewThreadsResolveTool:()=>Ao,githubPrReviewsSubmitTool:()=>jo,githubToolsProject:()=>Su});var Su,Qs=h(()=>{"use strict";l();qs();Ws();Us();Gs();Bs();Hs();Ks();Js();Vs();qs();Ws();Us();Gs();Bs();Hs();Ks();Js();Vs();Su={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:"github"},tools:[Eo,Do,Mo,Ao,No,Oo,Io,jo,Lo],dependencies:{}}});var _u,Ru,$u,Eu,Du,Mu=h(()=>{"use strict";l();_u="web.fetch",Ru="Fetch",$u="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).",Eu="web",Du={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 Xs from"cheerio";function Au(r,e){let t=Xs.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 T of i){let b=t(T).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((T,b)=>{let w=t(b).text().trim();w.length>50&&c.length<3&&c.push(w)});let p=c.join(`
117
-
118
- `)||a.substring(0,500),m=[];t("h2, h3").each((T,b)=>{let w=t(b).text().trim();w&&w.length>5&&w.length<200&&m.length<10&&m.push(w)});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 Nu(r,e){let t=Xs.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 Ou(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 Iu(r){return`# ${r.title}
107
+ ${JSON.stringify(C)}`}catch{return`HTTP ${g.status} ${g.statusText}
108
+ ${T}`}}var Io,Ks=h(()=>{"use strict";l();Kd();Ne();_();xe();Io={name:Ud,displayName:Gd,description:Bd,parameters:Hd,category:zd,execute:_x}});var Jd,Vd,Qd,Xd,Yd,Zd=h(()=>{"use strict";l();Jd="github.pr.reviewThreads.resolve",Vd="Resolve Review Thread",Qd=["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(" "),Xd="github",Yd={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 Px(r,e){let t=String(r.threadId),o=await K(r.repo,r.token,e?.githubTokenStore,e?.config?.credentials);b(`[github.pr.reviewThreads.resolve] threadId=${t}`);let s=await fetch("https://api.github.com/graphql",{method:"POST",headers:Q(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 jo,Js=h(()=>{"use strict";l();Zd();Ne();_();xe();jo={name:Jd,displayName:Vd,description:Qd,parameters:Yd,category:Xd,execute:Px}});var eu,tu,ou,nu,ru,su=h(()=>{"use strict";l();eu="github.pr.reviewComments.reply",tu="Reply to Review Comment",ou="Reply within an existing PR review thread to maintain continuity.",nu="github",ru={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 Rx(r,e){let t=String(r.repo),o=Number(r.number),n=Number(r.inReplyTo),s=String(r.body),i=await K(t,r.token,e?.githubTokenStore,e?.config?.credentials),a=`https://api.github.com/repos/${t}/pulls/${o}/comments/${n}/replies`;b(`[github.pr.reviewComments.reply] repo=${t} inReplyTo=${n}`);let c=await fetch(a,{method:"POST",headers:Q(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();su();_();Ne();xe();Lo={name:eu,displayName:tu,description:ou,parameters:ru,category:nu,execute:Rx}});var iu,au,lu,cu,pu,mu=h(()=>{"use strict";l();iu="github.pr.diff.get",au="Get PR Diff",lu="Fetch the unified diff for a pull request (text/patch).",cu="github",pu={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 $x(r,e){let t=String(r.repo),o=Number(r.number),n=await K(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}`;b(`[github.pr.diff.get] repo=${t} pr=${o}`);let a=await fetch(i,{method:"GET",headers:Q(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"),d=`
111
+ \u2026 [truncated, ${s} of ${Qs.byteLength(c,"utf8")} bytes]`;return`HTTP ${a.status} ${a.statusText}
112
+ ${p}${d}`}return`HTTP ${a.status} ${a.statusText}
113
+ ${c}`}var Fo,Xs=h(()=>{"use strict";l();mu();Ne();_();xe();Fo={name:iu,displayName:au,description:lu,parameters:pu,category:cu,execute:$x}});var du,uu,fu,gu,hu,yu=h(()=>{"use strict";l();du="github.pr.files.list",uu="List PR Files",fu="List files changed in a PR with positions metadata.",gu="github",hu={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},perPage:{type:"integer",description:"Results per page (max 100)"},page:{type:"integer",description:"Page number"}},required:["repo","number"]}});async function Ex(r,e){let t=String(r.repo),o=Number(r.number),n=await K(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()}`:""}`;b(`[github.pr.files.list] repo=${t} pr=${o} perPage=${s??""} page=${i??""}`);let p=await fetch(c,{method:"GET",headers:Q(n)}),d=await p.text();return`HTTP ${p.status} ${p.statusText}
114
+ ${d}`}var qo,Ys=h(()=>{"use strict";l();yu();Ne();_();xe();qo={name:du,displayName:uu,description:fu,parameters:hu,category:gu,execute:Ex}});var bu,Tu,wu,xu,vu,Cu=h(()=>{"use strict";l();bu="github.pr.reviews.submit",Tu="Submit PR Review",wu="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",xu="github",vu={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 Dx(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 K(t,r.token,e?.githubTokenStore,e?.config?.credentials),c=`https://api.github.com/repos/${t}/pulls/${o}/reviews`;b(`[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 d=await fetch(c,{method:"POST",headers:Q(a,{"Content-Type":"application/json"}),body:JSON.stringify(p)}),m=await d.text();return`HTTP ${d.status} ${d.statusText}
115
+ ${m}`}var Wo,Zs=h(()=>{"use strict";l();Cu();Ne();_();xe();Wo={name:bu,displayName:Tu,description:wu,parameters:vu,category:xu,execute:Dx}});var ku,Su,_u,Pu,Ru,$u=h(()=>{"use strict";l();ku="github.issues.comments.create",Su="Create Issue/PR Comment",_u="Create a comment on an issue or pull request (conversation tab).",Pu="github",Ru={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 K(t,r.token,e?.githubTokenStore,e?.config?.credentials),i=`https://api.github.com/repos/${t}/issues/${o}/comments`;b(`[github.issues.comments.create] repo=${t} number=${o}`);let a=await fetch(i,{method:"POST",headers:Q(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),c=await a.text();return`HTTP ${a.status} ${a.statusText}
116
+ ${c}`}var Uo,ei=h(()=>{"use strict";l();$u();Ne();_();xe();Uo={name:ku,displayName:Su,description:_u,parameters:Ru,category:Pu,execute:Ax}});var Du={};re(Du,{githubContentsGetTextTool:()=>Oo,githubGraphqlExecuteTool:()=>No,githubIssuesCommentsCreateTool:()=>Uo,githubPrDiffGetTool:()=>Fo,githubPrFilesListTool:()=>qo,githubPrReviewCommentsReplyTool:()=>Lo,githubPrReviewThreadsListTool:()=>Io,githubPrReviewThreadsResolveTool:()=>jo,githubPrReviewsSubmitTool:()=>Wo,githubToolsProject:()=>Eu});var Eu,ti=h(()=>{"use strict";l();zs();Hs();Ks();Js();Vs();Xs();Ys();Zs();ei();zs();Hs();Ks();Js();Vs();Xs();Ys();Zs();ei();Eu={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:"github"},tools:[No,Oo,Io,jo,Lo,Fo,qo,Wo,Uo],dependencies:{}}});var Au,Mu,Nu,Ou,Iu,ju=h(()=>{"use strict";l();Au="web.fetch",Mu="Fetch",Nu="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).",Ou="web",Iu={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 T of i){let y=t(T).first();if(y.length>0&&(a=y.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let c=[];t("p").each((T,y)=>{let w=t(y).text().trim();w.length>50&&c.length<3&&c.push(w)});let p=c.join(`
117
+
118
+ `)||a.substring(0,500),d=[];t("h2, h3").each((T,y)=>{let w=t(y).text().trim();w&&w.length>5&&w.length<200&&d.length<10&&d.push(w)});let m=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:d,wordCount:m}}function Fu(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 qu(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 Wu(r){return`# ${r.title}
120
120
  URL: ${r.url}
121
121
 
122
- ${r.snippet}`}var ju=h(()=>{"use strict";l()});async function Rx(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=Au(c,e);return Ou(p)}else if(t==="minimal"){let p=Nu(c,e);return Iu(p)}else return c.length>15e3?c.substring(0,15e3)+`
122
+ ${r.snippet}`}var Uu=h(()=>{"use strict";l()});async function Mx(r){let e=r.url,t=r.extractionMode||"full",o=r.headers,n=r.timeout||3e4;if(b(`[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 qu(p)}else if(t==="minimal"){let p=Fu(c,e);return Wu(p)}else return c.length>15e3?c.substring(0,15e3)+`
124
124
 
125
- [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var Fo,Ys=h(()=>{"use strict";l();Mu();ju();S();Fo={name:_u,displayName:Ru,description:$u,parameters:Du,category:Eu,execute:Rx}});var Lu,Fu,qu,Wu,Uu,Gu=h(()=>{"use strict";l();Lu="web.search",Fu="Search",qu="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.",Wu="web",Uu={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 zu from"cheerio";function Dx(r,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=zu.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 Mx(r){if(r)switch(r){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function Bu(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 Ax(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 T=new AbortController,b=setTimeout(()=>T.abort(),r.timeout||3e4);return{signal:T.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:T,clear:b}=a(),w=Mx(s),k={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:c,query:t,max_results:o,include_answer:n,...w&&{days:w}}),signal:T};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 pe(`[web.search] Tavily search failed with status ${v.status}`)}catch(T){pe(`[web.search] Tavily search failed, falling back: ${T}`)}}if(p)try{let{signal:T,clear:b}=a();if(n){let w=Bu(s),k=w?`&freshness=${w}`:"",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:T}).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 ee=await $.json(),F=x.web.results.slice(0,o).map(q=>({title:q.title,link:q.url,snippet:q.description})),G=ee.summary?.map(q=>q.data).join(`
126
- `)||ee.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 w=Bu(s),k=w?`&freshness=${w}`:"",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:T}).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(T){O(`[web.search] Brave search failed, falling back: ${T}`)}let{signal:m,clear:d}=a(),g;try{g=await fetch($x,{method:"POST",headers:{"User-Agent":Ex,"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(T){throw T.name==="AbortError"?new Error(i):T}finally{d()}if(g.ok){let T=await g.text(),b=Dx(T,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 $x,Ex,qo,Zs=h(()=>{"use strict";l();Gu();S();$x="https://lite.duckduckgo.com/lite/",Ex="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";qo={name:Lu,displayName:Fu,description:qu,parameters:Uu,category:Wu,execute:Ax}});var Hu,Ku,Ju,Vu,Qu,Xu=h(()=>{"use strict";l();Hu="web.scrape",Ku="Scrape",Ju="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.",Vu="web",Qu={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 ef from"cheerio";async function Ix(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":Nx},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=ef.load(m);for(let b of Ox)d(b).remove();if(n==="tables"){let b=[];return d("table").each((w,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((ee,F)=>{let G=d(F).text().trim();x.length>0&&x[ee]?E[x[ee]]=G:E.push(G)}),v.push(E))}),v.length>0&&b.push({id:`Table ${w+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(),w=null,k=0;if(d("h1, h2, h3, h4, h5, h6").each((v,x)=>{if(d(x).text().toLowerCase().includes(b))return w=x,k=parseInt(x.tagName.charAt(1)),!1}),w){let v=d(w),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(`
125
+ [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var Go,ni=h(()=>{"use strict";l();ju();Uu();_();Go={name:Au,displayName:Mu,description:Nu,parameters:Iu,category:Ou,execute:Mx}});var Gu,Bu,zu,Hu,Ku,Ju=h(()=>{"use strict";l();Gu="web.search",Bu="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.",Hu="web",Ku={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 Qu from"cheerio";function Ix(r,e){b("[web.search] Parsing DuckDuckGo Lite response");let t=Qu.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"),d=a.siblings(".result-snippet").text().trim();d||(d=a.parent().text().replace(c,"").trim()),c&&p&&o.push({title:c,link:p,snippet:d.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 Vu(r){if(!r)return"";switch(r){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return""}}async function Lx(r,e){let t=r.query,o=r.max_results||5,n=r.include_answer||!1,s=r.freshness;b(`[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 T=new AbortController,y=setTimeout(()=>T.abort(),r.timeout||3e4);return{signal:T.signal,clear:()=>clearTimeout(y)}};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){b("[web.search] using Tavily API");try{let{signal:T,clear:y}=a(),w=jx(s),k={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:c,query:t,max_results:o,include_answer:n,...w&&{days:w}}),signal:T};b(`[web.search] Tavily request=${JSON.stringify(k)}`);let C=await fetch("https://api.tavily.com/search",k).finally(y);if(C.ok){let x=await C.json();if(x.results&&x.results.length>0){let v=x.results.map(P=>({title:P.title,link:P.url,snippet:P.content}));return n&&x.answer?JSON.stringify({answer:x.answer,results:v},null,2):JSON.stringify(v,null,2)}}else ue(`[web.search] Tavily search failed with status ${C.status}`)}catch(T){ue(`[web.search] Tavily search failed, falling back: ${T}`)}}if(p)try{let{signal:T,clear:y}=a();if(n){let w=Vu(s),k=w?`&freshness=${w}`:"",C=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:T}).finally(y);if(C.ok){let x=await C.json(),v=x.summarizer?.key;if(v&&x.web?.results){let{signal:P,clear:E}=a(),j=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${v}`,{headers:{Accept:"application/json","X-Subscription-Token":p},signal:P}).finally(E);if(j.ok){let R=await j.json(),te=x.web.results.slice(0,o).map(Y=>({title:Y.title,link:Y.url,snippet:Y.description})),B=R.summary?.map(Y=>Y.data).join(`
126
+ `)||R.title;return JSON.stringify({answer:B,results:te},null,2)}}if(x.web?.results){let P=x.web.results.slice(0,o).map(E=>({title:E.title,link:E.url,snippet:E.description}));return JSON.stringify(P,null,2)}}}else{let w=Vu(s),k=w?`&freshness=${w}`:"",C=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:T}).finally(y);if(C.ok){let x=await C.json();if(x.web?.results&&x.web.results.length>0){let v=x.web.results.slice(0,o).map(P=>({title:P.title,link:P.url,snippet:P.description}));return JSON.stringify(v,null,2)}}}}catch(T){M(`[web.search] Brave search failed, falling back: ${T}`)}let{signal:d,clear:m}=a(),g;try{g=await fetch(Nx,{method:"POST",headers:{"User-Agent":Ox,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:t}).toString(),signal:d})}catch(T){throw T.name==="AbortError"?new Error(i):T}finally{m()}if(g.ok){let T=await g.text(),y=Ix(T,o);if(y.length>0)return JSON.stringify(y,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 Nx,Ox,Bo,ri=h(()=>{"use strict";l();Ju();_();Nx="https://lite.duckduckgo.com/lite/",Ox="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";Bo={name:Gu,displayName:Bu,description:zu,parameters:Ku,category:Hu,execute:Lx}});var Xu,Yu,Zu,ef,tf,of=h(()=>{"use strict";l();Xu="web.scrape",Yu="Scrape",Zu="Extract clean text content from a webpage. RECOMMENDED WORKFLOW: Use web.map first to see page structure, then use section parameter to extract specific sections. Strips scripts, styles, navigation, and other junk. By default, auto-detects and extracts the main article/content area.",ef="web",tf={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as sf from"cheerio";async function Wx(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(b(`[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":Fx},signal:a.signal})}catch(y){throw y.name==="AbortError"?new Error(`Request timed out after ${i}ms`):y}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let d=await p.text(),m=sf.load(d);for(let y of qx)m(y).remove();if(n==="tables"){let y=[];return m("table").each((w,k)=>{let C=[],x=[];m(k).find("th").each((v,P)=>{x.push(m(P).text().trim())}),m(k).find("tr").each((v,P)=>{let E=x.length>0?{}:[],j=m(P).find("td");j.length>0&&(j.each((R,te)=>{let B=m(te).text().trim();x.length>0&&x[R]?E[x[R]]=B:E.push(B)}),C.push(E))}),C.length>0&&y.push({id:`Table ${w+1}`,headers:x.length>0?x:void 0,rows:C})}),y.length===0?`No tables found on ${e}`:JSON.stringify(y,null,2)}let g="";if(o){let y=o.toLowerCase(),w=null,k=0;if(m("h1, h2, h3, h4, h5, h6").each((C,x)=>{if(m(x).text().toLowerCase().includes(y))return w=x,k=parseInt(x.tagName.charAt(1)),!1}),w){let C=m(w),x=[],v=C.next();for(;v.length>0;){let P=v.prop("tagName")?.toLowerCase();if(P&&/^h[1-6]$/.test(P)&&parseInt(P.charAt(1))<=k)break;let E=v.text().trim();E&&x.push(E),v=v.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 b=d(t);if(b.length>0)g=b.text().replace(/\s+/g," ").trim();else{for(let w of Yu){let k=d(w);if(k.length>0){let v=k.text().replace(/\s+/g," ").trim();if(v.length>Zu){g=v;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 y=m(t);if(y.length>0)g=y.text().replace(/\s+/g," ").trim();else{for(let w of nf){let k=m(w);if(k.length>0){let C=k.text().replace(/\s+/g," ").trim();if(C.length>rf){g=C;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 b of Yu){let w=d(b);if(w.length>0){let k=w.text().replace(/\s+/g," ").trim();if(k.length>Zu){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).]
136
+ ${g}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let y of nf){let w=m(y);if(w.length>0){let k=w.text().replace(/\s+/g," ").trim();if(k.length>rf){g=k;break}}}if(g||(g=m("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 b=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 y=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
- ${b}
144
+ ${y}
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 Nx,Ox,Yu,Zu,Wo,ei=h(()=>{"use strict";l();Xu();S();Nx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Ox=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Yu=["article","main",".content","#content",'[role="main"]',"body"],Zu=200;Wo={name:Hu,displayName:Ku,description:Ju,parameters:Qu,category:Vu,execute:Ix}});var tf,of,nf,rf,sf,af=h(()=>{"use strict";l();tf="web.extract_links",of="Extract Links",nf="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",rf="web",sf={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 lf from"cheerio";async function Lx(r){let e=r.url,t=r.filter,o=r.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let n=new AbortController,s=setTimeout(()=>n.abort(),o),i;try{i=await fetch(e,{method:"GET",headers:{"User-Agent":jx},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=lf.load(a),p=new URL(e),m=[];return c("a[href]").each((d,g)=>{let T=c(g),b=T.attr("href");if(!b)return;let w;try{w=new URL(b,e).toString()}catch{return}if(w.startsWith("javascript:")||w.startsWith("mailto:")||w.startsWith("tel:"))return;let k=T.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(w).hostname!==p.hostname)return}catch{return}else if(!w.includes(t))return}m.push({text:k,url:w})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var jx,Uo,ti=h(()=>{"use strict";l();af();jx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Uo={name:tf,displayName:of,description:nf,parameters:sf,category:rf,execute:Lx}});var cf,pf,mf,df,uf,ff=h(()=>{"use strict";l();cf="web.map",pf="Map",mf="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.",df="web",uf={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 gf from"cheerio";async function qx(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":Fx},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=gf.load(i),c=[];if(a("h1, h2, h3, h4, h5, h6").each((m,d)=>{let g=d.tagName.toLowerCase(),T=parseInt(g.charAt(1)),b=a(d).text().trim();b&&c.push({level:T,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}:
148
+ ${g}`}var Fx,qx,nf,rf,zo,si=h(()=>{"use strict";l();of();_();Fx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",qx=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],nf=["article","main",".content","#content",'[role="main"]',"body"],rf=200;zo={name:Xu,displayName:Yu,description:Zu,parameters:tf,category:ef,execute:Wx}});var af,lf,cf,pf,mf,df=h(()=>{"use strict";l();af="web.extract_links",lf="Extract Links",cf="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",pf="web",mf={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as uf from"cheerio";async function Gx(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":Ux},signal:n.signal})}catch(m){throw m.name==="AbortError"?new Error(`Request timed out after ${o}ms`):m}finally{clearTimeout(s)}if(!i.ok)throw new Error(`Failed to fetch ${e}: HTTP ${i.status} ${i.statusText}`);let a=await i.text(),c=uf.load(a),p=new URL(e),d=[];return c("a[href]").each((m,g)=>{let T=c(g),y=T.attr("href");if(!y)return;let w;try{w=new URL(y,e).toString()}catch{return}if(w.startsWith("javascript:")||w.startsWith("mailto:")||w.startsWith("tel:"))return;let k=T.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(w).hostname!==p.hostname)return}catch{return}else if(!w.includes(t))return}d.push({text:k,url:w})}),d.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(d,null,2)}var Ux,Ho,ii=h(()=>{"use strict";l();df();Ux="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:af,displayName:lf,description:cf,parameters:mf,category:pf,execute:Gx}});var ff,gf,hf,yf,bf,Tf=h(()=>{"use strict";l();ff="web.map",gf="Map",hf="Extract the structure/outline of a webpage by returning all headings (h1-h6). Use this FIRST when you need to understand what sections exist on a page before scraping specific content. Returns a lightweight outline showing the page hierarchy.",yf="web",bf={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as wf from"cheerio";async function zx(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":Bx},signal:o.signal})}catch(d){throw d.name==="AbortError"?new Error(`Request timed out after ${t}ms`):d}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((d,m)=>{let g=m.tagName.toLowerCase(),T=parseInt(g.charAt(1)),y=a(m).text().trim();y&&c.push({level:T,text:y})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
149
149
 
150
- `;for(let m of c){let d=" ".repeat(m.level-1);p+=`${d}${"#".repeat(m.level)} ${m.text}
151
- `}return p}var Fx,Go,oi=h(()=>{"use strict";l();ff();Fx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Go={name:cf,displayName:pf,description:mf,parameters:uf,category:df,execute:qx}});var hf,yf,bf,Tf,wf,xf=h(()=>{"use strict";l();hf="web.metadata",yf="Extract Metadata",bf="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Tf="web",wf={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 vf from"cheerio";async function Ux(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":Wx},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=vf.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 Wx,Bo,ni=h(()=>{"use strict";l();xf();Wx="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Bo={name:hf,displayName:yf,description:bf,parameters:wf,category:Tf,execute:Ux}});var Cf,kf,Sf,Pf,_f,Rf=h(()=>{"use strict";l();Cf="web.sitemap",kf="Extract Sitemap",Sf="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Pf="web",_f={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 $f from"cheerio";async function ri(r,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(r,{method:"GET",headers:{"User-Agent":Gx},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function Bx(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 ri(n,o),!i.ok&&s&&(n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ri(n,o))}catch(p){if(s)n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ri(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=$f.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((g,T)=>{c.length>=t||c.push({loc:p(T).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((g,T)=>{if(c.length>=t)return;let b=p(T);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 Gx,zo,si=h(()=>{"use strict";l();Rf();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:Cf,displayName:kf,description:Sf,parameters:_f,category:Pf,execute:Bx}});var Ef,Df,Mf,Af,Nf,Of=h(()=>{"use strict";l();Ef="web.feed",Df="Extract Feed",Mf="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",Af="web",Nf={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 If(){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 jf=h(()=>{"use strict";l()});async function zx(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 If();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 Ho,ii=h(()=>{"use strict";l();Of();jf();Ho={name:Ef,displayName:Df,description:Mf,parameters:Nf,category:Af,execute:zx}});var Lf,Ff,qf,Wf,Uf,Gf=h(()=>{"use strict";l();Lf="web.screenshot",Ff="Screenshot",qf="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",Wf="web",Uf={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 Bf(){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 zf=h(()=>{"use strict";l()});async function Kx(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 Bf()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(Hx),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 Hx,Ko,ai=h(()=>{"use strict";l();Gf();zf();Hx="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:Lf,displayName:Ff,description:qf,parameters:Uf,category:Wf,execute:Kx}});var Kf={};te(Kf,{webExtractLinksTool:()=>Uo,webFeedTool:()=>Ho,webFetchTool:()=>Fo,webMapTool:()=>Go,webMetadataTool:()=>Bo,webScrapeTool:()=>Wo,webScreenshotTool:()=>Ko,webSearchTool:()=>qo,webSitemapTool:()=>zo,webToolsProject:()=>Hf});var Hf,li=h(()=>{"use strict";l();Ys();Zs();ei();ti();oi();ni();si();ii();ai();Ys();Zs();ei();ti();oi();ni();si();ii();ai();Hf={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:"web"},tools:[Fo,qo,Wo,Uo,Go,Bo,zo,Ho,Ko],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Jf,Vf,Qf,Xf,Yf,Zf=h(()=>{"use strict";l();Jf="coding.find_symbol",Vf="Find Symbol",Qf="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Xf="coding",Yf={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 Jx}from"path";function Nn(r){let e=Jx(r).toLowerCase();return Vx[e]||"unknown"}var Vx,ci=h(()=>{"use strict";l();Vx={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});import*as it from"web-tree-sitter";import*as Ae from"fs";import*as Ge from"path";import*as tg from"os";var eg,pi,Qx,On,og=h(()=>{"use strict";l();eg=it.default||it.Parser||it,pi=Ge.join(tg.homedir(),".toolpack-sdk","grammars"),Qx=Ge.resolve(u,"../../grammars"),On=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await eg.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||eg.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(Qx,t);if(Ae.existsSync(n))return n;let s=Ge.join(pi,t);return Ae.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){Ae.existsSync(pi)||Ae.mkdirSync(pi,{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 Jo from"web-tree-sitter";import*as ng from"fs";import*as rg from"crypto";var Xx,In,sg=h(()=>{"use strict";l();ci();og();Xx=Jo.default||Jo.Parser||Jo,In=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new On}hash(e){return rg.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:ng.readFileSync(e,"utf-8"),n=this.hash(o),s=this.treeCache.get(e),i=Nn(e);if(i==="unknown")throw new Error(`Unsupported file type for ${e}`);let a=await this.grammarManager.ensureGrammar(i);if(s&&s.contentHash===n)return s.lastAccessed=Date.now(),{tree:s.tree,language:s.language,grammar:a};this.parser||(await this.grammarManager.init(),this.parser=new Xx),this.parser.setLanguage(a);let 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 Yx}from"@babel/parser";import*as mi from"@babel/traverse";var Ee,jn,ig=h(()=>{"use strict";l();Ee=mi.default||mi,jn=class{parseCode(e){return Yx(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 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);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 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);Ee(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 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,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);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
- `),c=Math.max(0,t-1),p=Math.min(a.length,n),m=a.slice(c,p).join(`
155
- `),d=`
150
+ `;for(let d of c){let m=" ".repeat(d.level-1);p+=`${m}${"#".repeat(d.level)} ${d.text}
151
+ `}return p}var Bx,Ko,ai=h(()=>{"use strict";l();Tf();Bx="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:ff,displayName:gf,description:hf,parameters:bf,category:yf,execute:zx}});var xf,vf,Cf,kf,Sf,_f=h(()=>{"use strict";l();xf="web.metadata",vf="Extract Metadata",Cf="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",kf="web",Sf={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Pf from"cheerio";async function Kx(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":Hx},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,d)=>{let m=a(d).attr("property")?.replace("og:",""),g=a(d).attr("content");m&&g&&(c.openGraph[m]=g)}),a('meta[name^="twitter:"]').each((p,d)=>{let m=a(d).attr("name")?.replace("twitter:",""),g=a(d).attr("content");m&&g&&(c.twitter[m]=g)}),a('script[type="application/ld+json"]').each((p,d)=>{let m=a(d).html();if(m)try{c.jsonLd.push(JSON.parse(m))}catch{}}),JSON.stringify(c,null,2)}var Hx,Jo,li=h(()=>{"use strict";l();_f();Hx="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:xf,displayName:vf,description:Cf,parameters:Sf,category:kf,execute:Kx}});var Rf,$f,Ef,Df,Af,Mf=h(()=>{"use strict";l();Rf="web.sitemap",$f="Extract Sitemap",Ef="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Df="web",Af={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 Nf 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":Jx},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function Vx(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=Nf.load(a,{xmlMode:!0}),d=p("sitemap > loc");if(d.length>0)return d.each((g,T)=>{c.length>=t||c.push({loc:p(T).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((g,T)=>{if(c.length>=t)return;let y=p(T);c.push({loc:y.children("loc").text(),lastmod:y.children("lastmod").text()||void 0,priority:y.children("priority").text()||void 0})})}else{let p=a.split(`
152
+ `);for(let d of p){if(c.length>=t)break;let m=d.trim();if(m.toLowerCase().startsWith("sitemap:"))c.push({loc:m.substring(8).trim()});else if(m.toLowerCase().startsWith("allow:")){let g=m.substring(6).trim();c.push({loc:new URL(g,n).toString()})}}}return JSON.stringify(c,null,2)}var Jx,Vo,pi=h(()=>{"use strict";l();Mf();Jx="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:Rf,displayName:$f,description:Ef,parameters:Af,category:Df,execute:Vx}});var Of,If,jf,Lf,Ff,qf=h(()=>{"use strict";l();Of="web.feed",If="Extract Feed",jf="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",Lf="web",Ff={type:"object",properties:{url:{type:"string",description:"The URL of the RSS/Atom feed"},max_entries:{type:"integer",description:"Maximum number of entries to return (default: 10)",default:10},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Wf(){try{let 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 Uf=h(()=>{"use strict";l()});async function Qx(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 Wf();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 Qo,mi=h(()=>{"use strict";l();qf();Uf();Qo={name:Of,displayName:If,description:jf,parameters:Ff,category:Lf,execute:Qx}});var Gf,Bf,zf,Hf,Kf,Jf=h(()=>{"use strict";l();Gf="web.screenshot",Bf="Screenshot",zf="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",Hf="web",Kf={type:"object",properties:{url:{type:"string",description:"The URL to capture"},format:{type:"string",description:'Output format: "html" or "png" (default: "html")',enum:["html","png"],default:"html"},viewport:{type:"object",description:"Optional viewport { width, height } (default: { width: 1280, height: 800 })",properties:{width:{type:"integer"},height:{type:"integer"}}},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Vf(){try{let r=await import("puppeteer");return r.default||r}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var Qf=h(()=>{"use strict";l()});async function Yx(r){let e=r.url,t=r.format||"html",o=r.viewport,n=r.timeout||3e4;if(!e)throw new Error("url is required");let i=await(await Vf()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(Xx),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 Xx,Xo,di=h(()=>{"use strict";l();Jf();Qf();Xx="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:Gf,displayName:Bf,description:zf,parameters:Kf,category:Hf,execute:Yx}});var Yf={};re(Yf,{webExtractLinksTool:()=>Ho,webFeedTool:()=>Qo,webFetchTool:()=>Go,webMapTool:()=>Ko,webMetadataTool:()=>Jo,webScrapeTool:()=>zo,webScreenshotTool:()=>Xo,webSearchTool:()=>Bo,webSitemapTool:()=>Vo,webToolsProject:()=>Xf});var Xf,ui=h(()=>{"use strict";l();ni();ri();si();ii();ai();li();pi();mi();di();ni();ri();si();ii();ai();li();pi();mi();di();Xf={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:"web"},tools:[Go,Bo,zo,Ho,Ko,Jo,Vo,Qo,Xo],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Zf,eg,tg,og,ng,rg=h(()=>{"use strict";l();Zf="coding.find_symbol",eg="Find Symbol",tg="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",og="coding",ng={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 Zx}from"path";function Ln(r){let e=Zx(r).toLowerCase();return ev[e]||"unknown"}var ev,fi=h(()=>{"use strict";l();ev={".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 ut from"web-tree-sitter";import*as je from"fs";import*as Ve from"path";import*as ig from"os";var sg,gi,tv,Fn,ag=h(()=>{"use strict";l();sg=ut.default||ut.Parser||ut,gi=Ve.join(ig.homedir(),".toolpack-sdk","grammars"),tv=Ve.resolve(u,"../../grammars"),Fn=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await sg.init({locateFile(e,t){return Ve.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(ut.Language||sg.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Ve.resolve(u,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(je.existsSync(o))return o;let n=Ve.join(tv,t);if(je.existsSync(n))return n;let s=Ve.join(gi,t);return je.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){je.existsSync(gi)||je.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);je.writeFileSync(t,i)}}});import*as Yo from"web-tree-sitter";import*as lg from"fs";import*as cg from"crypto";var ov,qn,pg=h(()=>{"use strict";l();fi();ag();ov=Yo.default||Yo.Parser||Yo,qn=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Fn}hash(e){return cg.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:lg.readFileSync(e,"utf-8"),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 ov),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 nv}from"@babel/parser";import*as hi from"@babel/traverse";var Oe,Wn,mg=h(()=>{"use strict";l();Oe=hi.default||hi,Wn=class{parseCode(e){return nv(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;Oe(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);Oe(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);Oe(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,d=c.local.name;i.push(p===d?p:`${p} as ${d}`),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);Oe(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 d=c.node.loc?.start.line||0,m=c.node.loc?.start.column||0,g=i[d-1]||"";n.push({file:e.filePath,line:d,column:m,context:g.trim(),isDeclaration:p})}}}})}catch{}return n}async getSymbolAtPosition(e,t,o){try{let n=this.parseCode(e.content),s=null;return Oe(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 Oe(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);Oe(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),d=a.slice(c,p).join(`
155
+ `),m=`
156
156
  function ${i}() {
157
- ${m}
157
+ ${d}
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="",c=0,p=0;if(Ee(n,{Function(b){let w=b.node.loc;w&&w.start.line<=t&&w.end&&w.end.line>=t&&(i=b,c=w.start.line,p=w.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=[];Ee(n,{CallExpression(b){let w=b.node.loc;if(!w||w.start.line<c||w.end&&w.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})}}),Ee(n,{CallExpression(b){let w=b.node.callee,k=!1;if((w.type==="Identifier"&&w.name===a||w.type==="MemberExpression"&&w.property.type==="Identifier"&&w.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()],T=[...new Map(d.map(b=>[`${b.name}:${b.line}`,b])).values()];return{file:s,name:a,line:c,column:p,callers:g,callees:T}}catch{return null}}}});function Ce(r,e){di[r]=e}var di,at=h(()=>{"use strict";l();di={}});var Zx,ag=h(()=>{"use strict";l();at();Zx={symbols:`
159
+ `,g=`${i}();`;return{newFunction:m,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(Oe(n,{Function(y){let w=y.node.loc;w&&w.start.line<=t&&w.end&&w.end.line>=t&&(i=y,c=w.start.line,p=w.start.column,y.node.type==="FunctionDeclaration"&&y.node.id?a=y.node.id.name:y.parent.type==="VariableDeclarator"&&y.parent.id.type==="Identifier"?a=y.parent.id.name:y.parent.type==="ClassMethod"||y.parent.type==="ObjectMethod"?y.parent.key.type==="Identifier"&&(a=y.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let d=[],m=[];Oe(n,{CallExpression(y){let w=y.node.loc;if(!w||w.start.line<c||w.end&&w.end.line>c+1e3)return;let k=!1,C=y;for(;C;){if(C.isFunction()&&C.node.type==="FunctionDeclaration"&&C.node.id?.name===a){k=!0;break}C=C.parentPath}if(!k)return;let x=y.node.callee,v="<unknown>";x.type==="Identifier"?v=x.name:x.type==="MemberExpression"&&x.property.type==="Identifier"&&(v=x.property.name),v!=="<unknown>"&&m.push({file:s,name:v,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}),Oe(n,{CallExpression(y){let w=y.node.callee,k=!1;if((w.type==="Identifier"&&w.name===a||w.type==="MemberExpression"&&w.property.type==="Identifier"&&w.property.name===a)&&(k=!0),k){let C="<global>",x=y;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}d.push({file:s,name:C,line:y.node.loc?.start.line||0,column:y.node.loc?.start.column||0})}}});let g=[...new Map(d.map(y=>[`${y.name}:${y.line}`,y])).values()],T=[...new Map(m.map(y=>[`${y.name}:${y.line}`,y])).values()];return{file:s,name:a,line:c,column:p,callers:g,callees:T}}catch{return null}}}});function Pe(r,e){yi[r]=e}var yi,ft=h(()=>{"use strict";l();yi={}});var rv,dg=h(()=>{"use strict";l();ft();rv={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
- `};Ce("python",Zx)});var ev,lg=h(()=>{"use strict";l();at();ev={symbols:`
177
+ `};Pe("python",rv)});var sv,ug=h(()=>{"use strict";l();ft();sv={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
- `};Ce("go",ev)});var tv,cg=h(()=>{"use strict";l();at();tv={symbols:`
205
+ `};Pe("go",sv)});var iv,fg=h(()=>{"use strict";l();ft();iv={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
- `};Ce("rust",tv)});var ov,pg=h(()=>{"use strict";l();at();ov={symbols:`
227
+ `};Pe("rust",iv)});var av,gg=h(()=>{"use strict";l();ft();av={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
- `};Ce("java",ov)});var mg,dg=h(()=>{"use strict";l();at();mg={symbols:`
248
+ `};Pe("java",av)});var hg,yg=h(()=>{"use strict";l();ft();hg={symbols:`
249
249
  (function_definition
250
250
  declarator: (function_declarator
251
251
  declarator: (identifier) @name.function)) @definition.function
@@ -266,48 +266,48 @@ ${m}
266
266
  (identifier) @reference
267
267
  (type_identifier) @reference
268
268
  (field_identifier) @reference
269
- `};Ce("cpp",mg);Ce("c",mg)});var Ln,ug=h(()=>{"use strict";l();at();ag();lg();cg();pg();dg();Ln=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=di[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(`
269
+ `};Pe("cpp",hg);Pe("c",hg)});var Un,bg=h(()=>{"use strict";l();ft();dg();ug();fg();gg();yg();Un=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
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="",T=e.filePath.split(".").pop()?.toLowerCase();return T==="py"||T==="pyi"?(d=`
271
+ `),c=Math.max(0,t-1),p=Math.min(a.length,n),d=a.slice(c,p).join(`
272
+ `),m="",g="",T=e.filePath.split(".").pop()?.toLowerCase();return T==="py"||T==="pyi"?(m=`
273
273
  def ${i}():
274
- ${m.split(`
275
- `).map(b=>" "+b).join(`
274
+ ${d.split(`
275
+ `).map(y=>" "+y).join(`
276
276
  `)}
277
- `,g=`${i}()`):T==="go"?(d=`
277
+ `,g=`${i}()`):T==="go"?(m=`
278
278
  func ${i}() {
279
- ${m}
279
+ ${d}
280
280
  }
281
- `,g=`${i}()`):T==="rs"?(d=`
281
+ `,g=`${i}()`):T==="rs"?(m=`
282
282
  fn ${i}() {
283
- ${m}
283
+ ${d}
284
284
  }
285
- `,g=`${i}();`):T==="sh"||T==="bash"?(d=`
285
+ `,g=`${i}();`):T==="sh"||T==="bash"?(m=`
286
286
  ${i}() {
287
- ${m}
287
+ ${d}
288
288
  }
289
- `,g=`${i}`):(d=`
289
+ `,g=`${i}`):(m=`
290
290
  void ${i}() {
291
- ${m}
291
+ ${d}
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 Fn,fg=h(()=>{"use strict";l();ci();ig();ug();Fn=class{constructor(e){this.context=e;this.babelParser=new jn,this.treeSitterParser=new Ln(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Nn(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 nv,statSync as rv,readdirSync as sv}from"fs";import{join as iv,extname as av}from"path";var qn,gg=h(()=>{"use strict";l();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=sv(e,{withFileTypes:!0});for(let n of o){let s=iv(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(av(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=rv(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=nv(e,"utf-8"),s=L.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 lv,L,Dt,be=h(()=>{"use strict";l();sg();fg();gg();lv=new In,L=new Fn(lv),Dt=new qn});import{readFileSync as cv,statSync as pv,readdirSync as mv}from"fs";import{join as dv,extname as uv}from"path";async function hg(r,e,t){try{let o=cv(r,"utf-8");return await L.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function yg(r,e,t){let o=[];try{let n=mv(r,{withFileTypes:!0});for(let s of n){let i=dv(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await yg(i,e,t);o.push(...a)}else if(s.isFile()&&fv.includes(uv(s.name))){let a=await hg(i,e,t);o.push(...a)}}}}catch{}return o}async function gv(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 yg(t,e,o);else if(n.isFile())s=await hg(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 fv,Vo,ui=h(()=>{"use strict";l();Zf();be();S();fv=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Vo={name:Jf,displayName:Vf,description:Qf,parameters:Yf,category:Xf,execute:gv}});var bg,Tg,wg,xg,vg,Cg=h(()=>{"use strict";l();bg="coding.get_symbols",Tg="Get Symbols",wg="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",xg="coding",vg={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 hv}from"fs";async function yv(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=hv(e,"utf-8"),s=await L.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 Qo,fi=h(()=>{"use strict";l();Cg();be();S();Qo={name:bg,displayName:Tg,description:wg,parameters:vg,category:xg,execute:yv}});var kg,Sg,Pg,_g,Rg,$g=h(()=>{"use strict";l();kg="coding.get_imports",Sg="Get Imports",Pg="List all import statements in a JavaScript/TypeScript file",_g="coding",Rg={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as bv}from"fs";async function Tv(r){let e=r.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=bv(e,"utf-8"),n=await L.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 Xo,gi=h(()=>{"use strict";l();$g();be();S();Xo={name:kg,displayName:Sg,description:Pg,parameters:Rg,category:_g,execute:Tv}});var Eg,Dg,Mg,Ag,Ng,Og=h(()=>{"use strict";l();Eg="coding.find_references",Dg="Find References",Mg="Find all references to a symbol across JavaScript/TypeScript files",Ag="coding",Ng={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 wv,statSync as xv}from"fs";async function Ig(r,e,t){try{let o=wv(r,"utf-8");return await L.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function vv(r,e,t){let o=[];await Dt.buildIndex(r);let n=await Dt.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await Ig(s,e,t);o.push(...i)}return o}async function Cv(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=xv(t),s;if(n.isDirectory())s=await vv(t,e,o);else if(n.isFile())s=await Ig(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 Yo,hi=h(()=>{"use strict";l();Og();be();S();Yo={name:Eg,displayName:Dg,description:Mg,parameters:Ng,category:Ag,execute:Cv}});var jg,Lg,Fg,qg,Wg,Ug=h(()=>{"use strict";l();jg="coding.go_to_definition",Lg="Go To Definition",Fg="Jump to the definition of a symbol at a specific location in a file",qg="coding",Wg={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});import{readFileSync as Gg,statSync as kv}from"fs";import{dirname as Sv}from"path";async function Pv(r,e,t){try{let o=Gg(r,"utf-8");return await L.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function Bg(r,e){try{let t=Gg(r,"utf-8");return await L.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function _v(r,e){await Dt.buildIndex(r);let t=await Dt.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await Bg(o,e);if(n)return n}return null}async function Rv(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 Pv(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await Bg(e,s);if(!i){let a=n||Sv(e);kv(a).isDirectory()&&(i=await _v(a,s))}return JSON.stringify(i?{found:!0,symbol:s,definition:i}:{found:!1,symbol:s,message:`Definition not found for symbol "${s}"`},null,2)}var Zo,yi=h(()=>{"use strict";l();Ug();be();Zo={name:jg,displayName:Lg,description:Fg,parameters:Wg,category:qg,execute:Rv}});var zg,Hg,Kg,Jg,Vg,Qg=h(()=>{"use strict";l();zg="coding.multi_file_edit",Hg="Multi-File Edit",Kg="Edit multiple files atomically with rollback on failure",Jg="coding",Vg={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 $v,writeFileSync as Xg,existsSync as Ev}from"fs";async function Dv(r){let e=r.edits,t=r.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let s of e){if(!s.file)throw new Error("Each edit must have a file property");if(!s.changes||!Array.isArray(s.changes))throw new Error("Each edit must have a changes array");if(!Ev(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=$v(s.file,"utf-8");t&&o.push({file:s.file,content:i});let a=i;for(let c of s.changes){if(!c.oldText)throw new Error("Each change must have oldText property");if(c.newText===void 0)throw new Error("Each change must have newText property");let p=(a.match(new RegExp(Mv(c.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${s.file}: "${c.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${s.file}: "${c.oldText.substring(0,50)}..." appears ${p} times`);a=a.replace(c.oldText,c.newText)}Xg(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{Xg(i.file,i.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${s.message}`)}throw new Error(`Multi-file edit failed: ${s.message}`)}}function Mv(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var en,bi=h(()=>{"use strict";l();Qg();en={name:zg,displayName:Hg,description:Kg,parameters:Vg,category:Jg,execute:Dv,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var Yg,Zg,eh,th,oh,nh=h(()=>{"use strict";l();Yg="coding.refactor_rename",Zg="Refactor Rename",eh="Rename a symbol across the entire codebase intelligently",th="coding",oh={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 Av,writeFileSync as Nv,readdirSync as Ov}from"fs";import{join as Iv,extname as jv}from"path";import{parse as Lv}from"@babel/parser";import*as Ti from"@babel/traverse";function Wv(r,e,t,o){let n=[];try{let s=Av(r,"utf-8"),i=s.split(`
294
- `),a=Lv(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(Fv(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],T=g.substring(0,m.column),b=g.substring(m.column+m.length);p[d]=T+t+b}}Nv(r,p.join(`
295
- `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function rh(r,e,t,o){let n=[];try{let s=Ov(r,{withFileTypes:!0});for(let i of s){let a=Iv(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...rh(a,e,t,o));else if(i.isFile()&&qv.includes(jv(i.name))){let c=Wv(a,e,t,o);c.occurrences>0&&n.push(c)}}}}catch{}return n}async function Uv(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=rh(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 Fv,qv,tn,wi=h(()=>{"use strict";l();nh();Fv=Ti.default||Ti,qv=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];tn={name:Yg,displayName:Zg,description:eh,parameters:oh,category:th,execute:Uv,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var sh,ih,ah,lh,ch,ph=h(()=>{"use strict";l();sh="coding.get_outline",ih="Get File Outline",ah="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",lh="coding",ch={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as Gv,statSync as Bv}from"fs";async function zv(r){let e=r.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!Bv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Gv(e,"utf-8"),o=L.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 on,xi=h(()=>{"use strict";l();ph();be();S();on={name:sh,displayName:ih,description:ah,parameters:ch,category:lh,execute:zv}});var mh,dh,uh,fh,gh,hh=h(()=>{"use strict";l();mh="coding.get_diagnostics",dh="Get File Diagnostics",uh="Gets syntax errors and warnings for a file utilizing AST parsing.",fh="coding",gh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as Hv,statSync as Kv}from"fs";async function Jv(r){let e=r.file;if(!e)throw new Error("file is required");try{if(!Kv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Hv(e,"utf-8"),o=L.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 nn,vi=h(()=>{"use strict";l();hh();be();nn={name:mh,displayName:dh,description:uh,parameters:gh,category:fh,execute:Jv}});var yh,bh,Th,wh,xh,vh=h(()=>{"use strict";l();yh="coding.get_exports",bh="Get File Exports",Th="Lists all symbols exported by a file.",wh="coding",xh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as Vv,statSync as Qv}from"fs";async function Xv(r){let e=r.file;if(y(`[coding.get-exports] 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=L.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 rn,Ci=h(()=>{"use strict";l();vh();be();S();rn={name:yh,displayName:bh,description:Th,parameters:xh,category:wh,execute:Xv}});var Ch,kh,Sh,Ph,_h,Rh=h(()=>{"use strict";l();Ch="coding.extract_function",kh="Extract Function",Sh="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Ph="coding",_h={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 Yv,statSync as Zv}from"fs";async function eC(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(!Zv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=Yv(e,"utf-8"),c=L.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 sn,ki=h(()=>{"use strict";l();Rh();be();sn={name:Ch,displayName:kh,description:Sh,parameters:_h,category:Ph,execute:eC}});var $h,Eh,Dh,Mh,Ah,Nh=h(()=>{"use strict";l();$h="coding.get_call_hierarchy",Eh="Get Call Hierarchy",Dh="Shows callers and callees of a specific function or method.",Mh="coding",Ah={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 tC,statSync as oC}from"fs";async function nC(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(!oC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=tC(e,"utf-8"),s=L.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 an,Si=h(()=>{"use strict";l();Nh();be();an={name:$h,displayName:Eh,description:Dh,parameters:Ah,category:Mh,execute:nC}});var Ih={};te(Ih,{codingExtractFunctionTool:()=>sn,codingFindReferencesTool:()=>Yo,codingFindSymbolTool:()=>Vo,codingGetCallHierarchyTool:()=>an,codingGetDiagnosticsTool:()=>nn,codingGetExportsTool:()=>rn,codingGetImportsTool:()=>Xo,codingGetOutlineTool:()=>on,codingGetSymbolsTool:()=>Qo,codingGoToDefinitionTool:()=>Zo,codingMultiFileEditTool:()=>en,codingRefactorRenameTool:()=>tn,codingToolsProject:()=>Oh});var Oh,Pi=h(()=>{"use strict";l();ui();fi();gi();hi();yi();bi();wi();xi();vi();Ci();ki();Si();ui();fi();gi();hi();yi();bi();wi();xi();vi();Ci();ki();Si();Oh={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:[Vo,Qo,Xo,Yo,Zo,on,nn,rn,sn,an,en,tn],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var jh,Lh=h(()=>{"use strict";l();jh={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 rC}from"simple-git";function U(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return rC(e)}var ke=h(()=>{"use strict";l()});var Wn,Fh=h(()=>{"use strict";l();Lh();ke();Wn={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:jh,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 qh,Wh=h(()=>{"use strict";l();qh={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 Un,Uh=h(()=>{"use strict";l();Wh();ke();Un={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:qh,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 Gh,Bh=h(()=>{"use strict";l();Gh={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 Gn,zh=h(()=>{"use strict";l();Bh();ke();Gn={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:Gh,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}
293
+ `,g=`${i}();`),{newFunction:m,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 Gn,Tg=h(()=>{"use strict";l();fi();mg();bg();Gn=class{constructor(e){this.context=e;this.babelParser=new Wn,this.treeSitterParser=new Un(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 lv,statSync as cv,readdirSync as pv}from"fs";import{join as mv,extname as dv}from"path";var Bn,wg=h(()=>{"use strict";l();ve();Bn=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=pv(e,{withFileTypes:!0});for(let n of o){let s=mv(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(dv(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=cv(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=lv(e,"utf-8"),s=W.getParser(e);this.removeFileFromIndex(e);let i=await s.getSymbols({filePath:e,content:n});for(let a of i){let c=this.data.symbolLocations.get(a.name);c?c.add(e):this.data.symbolLocations.set(a.name,new Set([e]))}this.fileMtimes.set(e,o)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,o]of this.data.symbolLocations.entries())o.delete(e),o.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let o=this.data.symbolLocations.get(e);return o?Array.from(o):[]}}});var uv,W,Ot,ve=h(()=>{"use strict";l();pg();Tg();wg();uv=new qn,W=new Gn(uv),Ot=new Bn});import{readFileSync as fv,statSync as gv,readdirSync as hv}from"fs";import{join as yv,extname as bv}from"path";async function xg(r,e,t){try{let o=fv(r,"utf-8");return await W.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function vg(r,e,t){let o=[];try{let n=hv(r,{withFileTypes:!0});for(let s of n){let i=yv(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await vg(i,e,t);o.push(...a)}else if(s.isFile()&&Tv.includes(bv(s.name))){let a=await xg(i,e,t);o.push(...a)}}}}catch{}return o}async function wv(r){let e=r.symbol,t=r.path,o=r.kind;if(b(`[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=gv(t),s;if(n.isDirectory())s=await vg(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,locations:s},null,2)}var Tv,Zo,bi=h(()=>{"use strict";l();rg();ve();_();Tv=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Zo={name:Zf,displayName:eg,description:tg,parameters:ng,category:og,execute:wv}});var Cg,kg,Sg,_g,Pg,Rg=h(()=>{"use strict";l();Cg="coding.get_symbols",kg="Get Symbols",Sg="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",_g="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 xv}from"fs";async function vv(r){let e=r.file,t=r.kind;if(b(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=xv(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 en,Ti=h(()=>{"use strict";l();Rg();ve();_();en={name:Cg,displayName:kg,description:Sg,parameters:Pg,category:_g,execute:vv}});var $g,Eg,Dg,Ag,Mg,Ng=h(()=>{"use strict";l();$g="coding.get_imports",Eg="Get Imports",Dg="List all import statements in a JavaScript/TypeScript file",Ag="coding",Mg={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as Cv}from"fs";async function kv(r){let e=r.file;if(b(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=Cv(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 tn,wi=h(()=>{"use strict";l();Ng();ve();_();tn={name:$g,displayName:Eg,description:Dg,parameters:Mg,category:Ag,execute:kv}});var Og,Ig,jg,Lg,Fg,qg=h(()=>{"use strict";l();Og="coding.find_references",Ig="Find References",jg="Find all references to a symbol across JavaScript/TypeScript files",Lg="coding",Fg={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 Sv,statSync as _v}from"fs";async function Wg(r,e,t){try{let o=Sv(r,"utf-8");return await W.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function Pv(r,e,t){let o=[];await Ot.buildIndex(r);let n=await Ot.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await Wg(s,e,t);o.push(...i)}return o}async function Rv(r){let e=r.symbol,t=r.path,o=r.includeDeclaration===!0;if(b(`[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 Pv(t,e,o);else if(n.isFile())s=await Wg(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 on,xi=h(()=>{"use strict";l();qg();ve();_();on={name:Og,displayName:Ig,description:jg,parameters:Fg,category:Lg,execute:Rv}});var Ug,Gg,Bg,zg,Hg,Kg=h(()=>{"use strict";l();Ug="coding.go_to_definition",Gg="Go To Definition",Bg="Jump to the definition of a symbol at a specific location in a file",zg="coding",Hg={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 Jg,statSync as $v}from"fs";import{dirname as Ev}from"path";async function Dv(r,e,t){try{let o=Jg(r,"utf-8");return await W.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function Vg(r,e){try{let t=Jg(r,"utf-8");return await W.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function Av(r,e){await Ot.buildIndex(r);let t=await Ot.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await Vg(o,e);if(n)return n}return null}async function Mv(r){let e=r.file,t=r.line,o=r.column,n=r.searchPath;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");let s=await Dv(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await Vg(e,s);if(!i){let a=n||Ev(e);$v(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 nn,vi=h(()=>{"use strict";l();Kg();ve();nn={name:Ug,displayName:Gg,description:Bg,parameters:Hg,category:zg,execute:Mv}});var Qg,Xg,Yg,Zg,eh,th=h(()=>{"use strict";l();Qg="coding.multi_file_edit",Xg="Multi-File Edit",Yg="Edit multiple files atomically with rollback on failure",Zg="coding",eh={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 Nv,writeFileSync as oh,existsSync as Ov}from"fs";async function Iv(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(!Ov(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=Nv(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)}oh(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{oh(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 rn,Ci=h(()=>{"use strict";l();th();rn={name:Qg,displayName:Xg,description:Yg,parameters:eh,category:Zg,execute:Iv,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var nh,rh,sh,ih,ah,lh=h(()=>{"use strict";l();nh="coding.refactor_rename",rh="Refactor Rename",sh="Rename a symbol across the entire codebase intelligently",ih="coding",ah={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 Lv,writeFileSync as Fv,readdirSync as qv}from"fs";import{join as Wv,extname as Uv}from"path";import{parse as Gv}from"@babel/parser";import*as ki from"@babel/traverse";function Hv(r,e,t,o){let n=[];try{let s=Lv(r,"utf-8"),i=s.split(`
294
+ `),a=Gv(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(Bv(a,{Identifier(p){if(p.node.name===e){let d=p.node.loc?.start.line||0,m=p.node.loc?.start.column||0;c.push({line:d,column:m,length:e.length}),n.push({file:r,line:d,column:m,oldName:e,newName:t})}}}),!o&&c.length>0){c.sort((d,m)=>d.line!==m.line?m.line-d.line:m.column-d.column);let p=[...i];for(let d of c){let m=d.line-1;if(m>=0&&m<p.length){let g=p[m],T=g.substring(0,d.column),y=g.substring(d.column+d.length);p[m]=T+t+y}}Fv(r,p.join(`
295
+ `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function ch(r,e,t,o){let n=[];try{let s=qv(r,{withFileTypes:!0});for(let i of s){let a=Wv(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...ch(a,e,t,o));else if(i.isFile()&&zv.includes(Uv(i.name))){let c=Hv(a,e,t,o);c.occurrences>0&&n.push(c)}}}}catch{}return n}async function Kv(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=ch(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 Bv,zv,sn,Si=h(()=>{"use strict";l();lh();Bv=ki.default||ki,zv=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];sn={name:nh,displayName:rh,description:sh,parameters:ah,category:ih,execute:Kv,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var ph,mh,dh,uh,fh,gh=h(()=>{"use strict";l();ph="coding.get_outline",mh="Get File Outline",dh="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",uh="coding",fh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as Jv,statSync as Vv}from"fs";async function Qv(r){let e=r.file;if(b(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!Vv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Jv(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 an,_i=h(()=>{"use strict";l();gh();ve();_();an={name:ph,displayName:mh,description:dh,parameters:fh,category:uh,execute:Qv}});var hh,yh,bh,Th,wh,xh=h(()=>{"use strict";l();hh="coding.get_diagnostics",yh="Get File Diagnostics",bh="Gets syntax errors and warnings for a file utilizing AST parsing.",Th="coding",wh={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as Xv,statSync as Yv}from"fs";async function Zv(r){let e=r.file;if(!e)throw new Error("file is required");try{if(!Yv(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Xv(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 ln,Pi=h(()=>{"use strict";l();xh();ve();ln={name:hh,displayName:yh,description:bh,parameters:wh,category:Th,execute:Zv}});var vh,Ch,kh,Sh,_h,Ph=h(()=>{"use strict";l();vh="coding.get_exports",Ch="Get File Exports",kh="Lists all symbols exported by a file.",Sh="coding",_h={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as eC,statSync as tC}from"fs";async function oC(r){let e=r.file;if(b(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!tC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=eC(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 cn,Ri=h(()=>{"use strict";l();Ph();ve();_();cn={name:vh,displayName:Ch,description:kh,parameters:_h,category:Sh,execute:oC}});var Rh,$h,Eh,Dh,Ah,Mh=h(()=>{"use strict";l();Rh="coding.extract_function",$h="Extract Function",Eh="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Dh="coding",Ah={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 nC,statSync as rC}from"fs";async function sC(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(!rC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=nC(e,"utf-8"),c=W.getParser(e);if(!c.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await c.extractFunction({filePath:e,content:a},t,o,n,s,i);return JSON.stringify({file:e,result:p},null,2)}catch(a){throw new Error(`Failed to extract function from file "${e}": ${a.message}`)}}var pn,$i=h(()=>{"use strict";l();Mh();ve();pn={name:Rh,displayName:$h,description:Eh,parameters:Ah,category:Dh,execute:sC}});var Nh,Oh,Ih,jh,Lh,Fh=h(()=>{"use strict";l();Nh="coding.get_call_hierarchy",Oh="Get Call Hierarchy",Ih="Shows callers and callees of a specific function or method.",jh="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 iC,statSync as aC}from"fs";async function lC(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(!aC(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=iC(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 mn,Ei=h(()=>{"use strict";l();Fh();ve();mn={name:Nh,displayName:Oh,description:Ih,parameters:Lh,category:jh,execute:lC}});var Wh={};re(Wh,{codingExtractFunctionTool:()=>pn,codingFindReferencesTool:()=>on,codingFindSymbolTool:()=>Zo,codingGetCallHierarchyTool:()=>mn,codingGetDiagnosticsTool:()=>ln,codingGetExportsTool:()=>cn,codingGetImportsTool:()=>tn,codingGetOutlineTool:()=>an,codingGetSymbolsTool:()=>en,codingGoToDefinitionTool:()=>nn,codingMultiFileEditTool:()=>rn,codingRefactorRenameTool:()=>sn,codingToolsProject:()=>qh});var qh,Di=h(()=>{"use strict";l();bi();Ti();wi();xi();vi();Ci();Si();_i();Pi();Ri();$i();Ei();bi();Ti();wi();xi();vi();Ci();Si();_i();Pi();Ri();$i();Ei();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:[Zo,en,tn,on,nn,an,ln,cn,pn,mn,rn,sn],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var Uh,Gh=h(()=>{"use strict";l();Uh={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 cC}from"simple-git";function G(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return cC(e)}var Re=h(()=>{"use strict";l()});var zn,Bh=h(()=>{"use strict";l();Gh();Re();zn={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:Uh,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 zh,Hh=h(()=>{"use strict";l();zh={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 Hn,Kh=h(()=>{"use strict";l();Hh();Re();Hn={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:zh,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 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 Jh,Vh=h(()=>{"use strict";l();Jh={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 Kn,Qh=h(()=>{"use strict";l();Vh();Re();Kn={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:Jh,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}
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 Hh,Kh=h(()=>{"use strict";l();Hh={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Bn,Jh=h(()=>{"use strict";l();Kh();ke();Bn={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:Hh,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 Vh,Qh=h(()=>{"use strict";l();Vh={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var zn,Xh=h(()=>{"use strict";l();Qh();ke();zn={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Vh,execute:async r=>{let e=r.message;try{let o=await U().commit(e);return o.commit?`Successfully committed changes.
301
+ `)}catch(n){return`Error getting git log: ${n instanceof Error?n.message:String(n)}`}}}});var Xh,Yh=h(()=>{"use strict";l();Xh={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Jn,Zh=h(()=>{"use strict";l();Yh();Re();Jn={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:Xh,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 ey,ty=h(()=>{"use strict";l();ey={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Vn,oy=h(()=>{"use strict";l();ty();Re();Vn={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:ey,execute:async r=>{let e=r.message;try{let o=await G().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 Yh,Zh=h(()=>{"use strict";l();Yh={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 Hn,ey=h(()=>{"use strict";l();Zh();ke();Hn={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:Yh,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 ty,oy=h(()=>{"use strict";l();ty={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Kn,ny=h(()=>{"use strict";l();oy();ke();Kn={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:ty,execute:async r=>{let e=r.remote;try{let t=U(),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 ny,ry=h(()=>{"use strict";l();ny={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 Qn,sy=h(()=>{"use strict";l();ry();Re();Qn={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:ny,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 iy,ay=h(()=>{"use strict";l();iy={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Xn,ly=h(()=>{"use strict";l();ay();Re();Xn={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:iy,execute:async r=>{let e=r.remote;try{let t=G(),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 ry,sy=h(()=>{"use strict";l();ry={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 Jn,iy=h(()=>{"use strict";l();sy();ke();Jn={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:ry,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 ay,ly=h(()=>{"use strict";l();ay={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Vn,cy=h(()=>{"use strict";l();ly();ke();Vn={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:ay,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 py,my=h(()=>{"use strict";l();py={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 ge from"fs/promises";import*as Qn from"path";async function dy(r){let e=0,t=await ge.readdir(r,{withFileTypes:!0});for(let o of t){let n=Qn.join(r,o.name);if(o.isDirectory())e+=await dy(n);else if(o.isFile()){let s=await ge.stat(n);e+=s.size}}return e}async function aC(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=Qn.resolve(s,m),g=U(s),T=r.registry.get(e);if(T)try{if(await ge.access(d),T.sha===t)return T.lastAccessedAt=Date.now(),d;await ge.rm(d,{recursive:!0,force:!0}),r.totalBytes=Math.max(0,r.totalBytes-T.sizeBytes),r.registry.delete(e)}catch{r.totalBytes=Math.max(0,r.totalBytes-T.sizeBytes),r.registry.delete(e)}else try{await ge.access(d),await ge.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 w=U(d);try{let v=["origin",t];n>0&&v.push("--depth",n.toString()),await w.fetch(v)}catch{}await w.checkout(["--force",t]);let k=await dy(d);return r.totalBytes+=k,r.registry.set(e,{cloneDir:d,repo:e,sha:t,sizeBytes:k,lastAccessedAt:Date.now()}),d}catch(w){try{await ge.rm(d,{recursive:!0,force:!0})}catch{}throw w}}function lC(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}function _i(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:py,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??sC,p=parseInt(process.env.TOOLPACK_GIT_CLONE_MAX_BYTES??"0",10)||iC,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 ge.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 T=await aC(r,o,n,s,i,c,t?.githubTokenStore,t?.config?.credentials);return JSON.stringify({cloneDir:T,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."})}catch(g){return`Error cloning repository: ${lC(g)}`}finally{d()}}}}var sC,iC,Xn,uy=h(()=>{"use strict";l();my();ke();ye();Xr();sC=".toolpack/clones",iC=5e9;Xn=_i(Ha)});var gy={};te(gy,{createGitCloneTool:()=>_i,gitAddTool:()=>Bn,gitBlameTool:()=>Hn,gitBranchCreateTool:()=>Jn,gitBranchListTool:()=>Kn,gitCheckoutTool:()=>Vn,gitCloneTool:()=>Xn,gitCommitTool:()=>zn,gitDiffTool:()=>Un,gitLogTool:()=>Gn,gitStatusTool:()=>Wn,gitToolsProject:()=>fy});var fy,Ri=h(()=>{"use strict";l();Fh();Uh();zh();Jh();Xh();ey();ny();iy();cy();uy();fy={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:[Wn,Un,Gn,Bn,zn,Hn,Kn,Jn,Vn,Xn],dependencies:{"simple-git":"^3.27.0"}}});var hy,yy=h(()=>{"use strict";l();hy={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 by from"diff";var Yn,Ty=h(()=>{"use strict";l();yy();S();Yn={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:hy,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 by.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var wy,xy=h(()=>{"use strict";l();wy={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});import*as Cy from"diff";import{promises as vy}from"fs";var Zn,ky=h(()=>{"use strict";l();xy();S();Zn={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:wy,execute:async r=>{let e=r.path,t=r.patch;y(`[diff.apply] execute path="${e}"`);try{let o=await vy.readFile(e,"utf8"),n=Cy.applyPatch(o,t);return n===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await vy.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 Sy,Py=h(()=>{"use strict";l();Sy={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 _y from"diff";import{promises as cC}from"fs";var er,Ry=h(()=>{"use strict";l();Py();er={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:Sy,execute:async r=>{let e=r.path,t=r.patch;try{let o=await cC.readFile(e,"utf8"),n=_y.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 cy,py=h(()=>{"use strict";l();cy={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 Yn,my=h(()=>{"use strict";l();py();Re();Yn={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:cy,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 dy,uy=h(()=>{"use strict";l();dy={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Zn,fy=h(()=>{"use strict";l();uy();Re();Zn={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:dy,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 gy,hy=h(()=>{"use strict";l();gy={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 be from"fs/promises";import*as er from"path";async function yy(r){let e=0,t=await be.readdir(r,{withFileTypes:!0});for(let o of t){let n=er.join(r,o.name);if(o.isDirectory())e+=await yy(n);else if(o.isFile()){let s=await be.stat(n);e+=s.size}}return e}async function dC(r,e,t,o,n,s,i,a){let p=`https://x-access-token:${await K(e,void 0,i,a)}@github.com/${e}.git`,d=e.replace("/","_"),m=er.resolve(s,d),g=G(s),T=r.registry.get(e);if(T)try{if(await be.access(m),T.sha===t)return T.lastAccessedAt=Date.now(),m;await be.rm(m,{recursive:!0,force:!0}),r.totalBytes=Math.max(0,r.totalBytes-T.sizeBytes),r.registry.delete(e)}catch{r.totalBytes=Math.max(0,r.totalBytes-T.sizeBytes),r.registry.delete(e)}else try{await be.access(m),await be.rm(m,{recursive:!0,force:!0})}catch{}let y=["--no-checkout"];n>0&&y.push("--depth",n.toString()),o&&o!=="none"&&y.push("--filter",o);try{await g.clone(p,d,y);let w=G(m);try{let C=["origin",t];n>0&&C.push("--depth",n.toString()),await w.fetch(C)}catch{}await w.checkout(["--force",t]);let k=await yy(m);return r.totalBytes+=k,r.registry.set(e,{cloneDir:m,repo:e,sha:t,sizeBytes:k,lastAccessedAt:Date.now()}),m}catch(w){try{await be.rm(m,{recursive:!0,force:!0})}catch{}throw w}}function uC(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}function Ai(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:gy,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??pC,p=parseInt(process.env.TOOLPACK_GIT_CLONE_MAX_BYTES??"0",10)||mC,d=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 be.mkdir(c,{recursive:!0});let m=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,d);let T=await dC(r,o,n,s,i,c,t?.githubTokenStore,t?.config?.credentials);return JSON.stringify({cloneDir:T,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."})}catch(g){return`Error cloning repository: ${uC(g)}`}finally{m()}}}}var pC,mC,tr,by=h(()=>{"use strict";l();hy();Re();xe();os();pC=".toolpack/clones",mC=5e9;tr=Ai(Xa)});var wy={};re(wy,{createGitCloneTool:()=>Ai,gitAddTool:()=>Jn,gitBlameTool:()=>Qn,gitBranchCreateTool:()=>Yn,gitBranchListTool:()=>Xn,gitCheckoutTool:()=>Zn,gitCloneTool:()=>tr,gitCommitTool:()=>Vn,gitDiffTool:()=>Hn,gitLogTool:()=>Kn,gitStatusTool:()=>zn,gitToolsProject:()=>Ty});var Ty,Mi=h(()=>{"use strict";l();Bh();Kh();Qh();Zh();oy();sy();ly();my();fy();by();Ty={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:[zn,Hn,Kn,Jn,Vn,Qn,Xn,Yn,Zn,tr],dependencies:{"simple-git":"^3.27.0"}}});var xy,vy=h(()=>{"use strict";l();xy={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 Cy from"diff";var or,ky=h(()=>{"use strict";l();vy();_();or={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:xy,execute:async r=>{let e=r.oldContent,t=r.newContent,o=r.fileName||"file",n=r.contextLines??4;b(`[diff.create] execute fileName="${o}" contextLines=${n}`);try{return Cy.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var Sy,_y=h(()=>{"use strict";l();Sy={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 Ry from"diff";import{promises as Py}from"fs";var nr,$y=h(()=>{"use strict";l();_y();_();nr={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Sy,execute:async r=>{let e=r.path,t=r.patch;b(`[diff.apply] execute path="${e}"`);try{let o=await Py.readFile(e,"utf8"),n=Ry.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 Ey,Dy=h(()=>{"use strict";l();Ey={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 Ay from"diff";import{promises as fC}from"fs";var rr,My=h(()=>{"use strict";l();Dy();rr={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:Ey,execute:async r=>{let e=r.path,t=r.patch;try{let o=await fC.readFile(e,"utf8"),n=Ay.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 Ey={};te(Ey,{diffApplyTool:()=>Zn,diffCreateTool:()=>Yn,diffPreviewTool:()=>er,diffToolsProject:()=>$y});var $y,$i=h(()=>{"use strict";l();Ty();ky();Ry();$y={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:[Yn,Zn,er],dependencies:{diff:"^7.0.0"}}});var Dy,My=h(()=>{"use strict";l();Dy={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,tr=h(()=>{"use strict";l();Be=class{connectionString;constructor(e){this.connectionString=e}}});import Ay from"better-sqlite3";import*as Ei from"fs";var ln,Ny=h(()=>{"use strict";l();tr();ln=class extends Be{getDb(){if(!Ei.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Ay(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(!Ei.existsSync(e))throw new Error(`Database file not found: ${e}`);let n=new Ay(e,{readonly:!1});try{let s=n.prepare(t);return s.reader?s.all(o):s.run(o)}finally{n.close()}}}});import pC from"pg";var or,Oy=h(()=>{"use strict";l();tr();or=class extends Be{async getClient(){let e=new pC.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 Oy={};re(Oy,{diffApplyTool:()=>nr,diffCreateTool:()=>or,diffPreviewTool:()=>rr,diffToolsProject:()=>Ny});var Ny,Ni=h(()=>{"use strict";l();ky();$y();My();Ny={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:[or,nr,rr],dependencies:{diff:"^7.0.0"}}});var Iy,jy=h(()=>{"use strict";l();Iy={type:"object",properties:{db:{type:"string",description:"Database connection URI (e.g. postgres://user:pass@host/db, mysql://...) or local SQLite file path (.sqlite, .db)"},sql:{type:"string",description:"The SQL query to execute"},params:{type:"array",description:"Optional array of parameters for parameterized queries (to prevent SQL injection)",items:{},default:[]}},required:["db","sql"]}});var Qe,sr=h(()=>{"use strict";l();Qe=class{connectionString;constructor(e){this.connectionString=e}}});import Ly from"better-sqlite3";import*as Oi from"fs";var dn,Fy=h(()=>{"use strict";l();sr();dn=class extends Qe{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 gC from"pg";var ir,qy=h(()=>{"use strict";l();sr();ir=class extends Qe{async getClient(){let e=new gC.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 mC from"mysql2/promise";var nr,Iy=h(()=>{"use strict";l();tr();nr=class extends Be{async getConnection(){return await mC.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 ne,ze=h(()=>{"use strict";l();Ny();Oy();Iy();ne=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new or(e):e.startsWith("mysql://")?new nr(e):e.startsWith("sqlite://")?new ln(e.replace("sqlite://","")):new ln(e)}}});var rr,jy=h(()=>{"use strict";l();My();ze();S();rr={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Dy,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 ne.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 Ly,Fy=h(()=>{"use strict";l();Ly={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var sr,qy=h(()=>{"use strict";l();Fy();ze();sr={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Ly,execute:async r=>{let e=r.db,t=r.table;try{let n=await ne.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var Wy,Uy=h(()=>{"use strict";l();Wy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var ir,Gy=h(()=>{"use strict";l();Uy();ze();ir={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:Wy,execute:async r=>{let e=r.db;try{let o=await ne.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var By,zy=h(()=>{"use strict";l();By={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 ar,Hy=h(()=>{"use strict";l();zy();ze();ar={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:By,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 ne.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 Ky,Jy=h(()=>{"use strict";l();Ky={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 lr,Vy=h(()=>{"use strict";l();Jy();ze();lr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:Ky,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 ne.getAdapter(e).execute(a,i);return JSON.stringify(p,null,2)}catch(s){return`Database update error: ${s instanceof Error?s.message:String(s)}`}},confirmation:{level:"high",reason:"This will update database rows, potentially affecting multiple records.",showArgs:["table","data","where"]}}});var Qy,Xy=h(()=>{"use strict";l();Qy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var cr,Yy=h(()=>{"use strict";l();Xy();ze();cr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:Qy,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await ne.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 Zy,eb=h(()=>{"use strict";l();Zy={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 pr,tb=h(()=>{"use strict";l();eb();ze();pr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:Zy,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 ne.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 nb={};te(nb,{dbCountTool:()=>pr,dbDeleteTool:()=>cr,dbInsertTool:()=>ar,dbQueryTool:()=>rr,dbSchemaTool:()=>sr,dbTablesTool:()=>ir,dbToolsProject:()=>ob,dbUpdateTool:()=>lr});var ob,Di=h(()=>{"use strict";l();jy();qy();Gy();Hy();Vy();Yy();tb();ob={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:[rr,sr,ir,ar,lr,cr,pr],dependencies:{"better-sqlite3":"^11.3.0"}}});var rb,sb=h(()=>{"use strict";l();rb={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 dC}from"netlify";var He,mr=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 dC(t)}}});var dr,ib=h(()=>{"use strict";l();sb();mr();S();dr={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:rb,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 ab,lb=h(()=>{"use strict";l();ab={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},deployId:{type:"string",description:"The specific Deployment ID to check"}},required:["siteId","deployId"]}});var ur,cb=h(()=>{"use strict";l();lb();mr();ur={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:ab,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 pb,mb=h(()=>{"use strict";l();pb={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},limit:{type:"number",description:"Number of recent deployments to return. Defaults to 5.",default:5}},required:["siteId"]}});var fr,db=h(()=>{"use strict";l();mb();mr();S();fr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:pb,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 fb={};te(fb,{cloudDeployTool:()=>dr,cloudListTool:()=>fr,cloudStatusTool:()=>ur,cloudToolsProject:()=>ub});var ub,Mi=h(()=>{"use strict";l();ib();cb();db();ub={manifest:{key:"cloud",name:"cloud-tools",displayName:"Cloud Deployment",version:"1.0.0",description:"Cloud deployment operations allowing the AI to publish directories directly to the internet.",author:"Sajeer",tools:["cloud.deploy","cloud.status","cloud.list"],category:"cloud"},tools:[dr,ur,fr],dependencies:{netlify:"^13.1.20"}}});var gb,hb,yb,bb,Tb,wb=h(()=>{"use strict";l();gb="slack.chat.postMessage",hb="Post Slack Message",yb="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.",bb="slack",Tb={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 uC(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}}async function we(r,e,t){let o=await fetch(`https://slack.com/api/${r}`,{method:"POST",headers:uC(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 fC(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 we("chat.postMessage",i,a),p=c.ts??"";return`Message posted. channel=${c.channel??t} ts=${p}`}var cn,Ai=h(()=>{"use strict";l();wb();lt();ct();cn={name:gb,displayName:hb,description:yb,parameters:Tb,category:bb,execute:fC}});var xb,vb,Cb,kb,Sb,Pb=h(()=>{"use strict";l();xb="slack.chat.postEphemeral",vb="Post Ephemeral Slack Message",Cb="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.",kb="slack",Sb={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 gC(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 we("chat.postEphemeral",i,a),`Ephemeral message sent to user=${o} in channel=${t}.`}var pn,Ni=h(()=>{"use strict";l();Pb();lt();ct();pn={name:xb,displayName:vb,description:Cb,parameters:Sb,category:kb,execute:gC}});var _b,Rb,$b,Eb,Db,Mb=h(()=>{"use strict";l();_b="slack.reactions.add",Rb="Add Slack Reaction",$b="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.",Eb="slack",Db={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 hC(r,e){let t=String(r.channel),o=String(r.timestamp),n=String(r.name),s=Te(r.token,e?.config?.credentials);try{await we("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 mn,Oi=h(()=>{"use strict";l();Mb();lt();ct();mn={name:_b,displayName:Rb,description:$b,parameters:Db,category:Eb,execute:hC}});var Ab,Nb,Ob,Ib,jb,Lb=h(()=>{"use strict";l();Ab="slack.conversations.history",Nb="Get Slack Channel History",Ob="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.",Ib="slack",jb={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 yC(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 we("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 dn,Ii=h(()=>{"use strict";l();Lb();lt();ct();dn={name:Ab,displayName:Nb,description:Ob,parameters:jb,category:Ib,execute:yC}});var Fb,qb,Wb,Ub,Gb,Bb=h(()=>{"use strict";l();Fb="slack.conversations.replies",qb="Get Slack Thread Replies",Wb="Fetch all replies in a Slack thread. Use this to read the full conversation history of a thread, including who replied and when. Requires the channel ID and the timestamp (ts) of the parent message that started the thread.",Ub="slack",Gb={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 bC(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 we("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",T=d===0?" [parent]":"",b=(m.text??"").replace(/\n/g," ").slice(0,200);return`[${m.ts}] ${g}${T}: ${b}`}).join(`
320
- `)}var un,ji=h(()=>{"use strict";l();Bb();lt();ct();un={name:Fb,displayName:qb,description:Wb,parameters:Gb,category:Ub,execute:bC}});var zb,Hb,Kb,Jb,Vb,Qb=h(()=>{"use strict";l();zb="slack.auth.test",Hb="Slack Auth Test",Kb="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.",Jb="slack",Vb={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function TC(r,e){let t=Te(r.token,e?.config?.credentials),o=await we("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 fn,Li=h(()=>{"use strict";l();Qb();lt();ct();fn={name:zb,displayName:Hb,description:Kb,parameters:Vb,category:Jb,execute:TC}});var Yb={};te(Yb,{slackAuthTestTool:()=>fn,slackChatPostEphemeralTool:()=>pn,slackChatPostMessageTool:()=>cn,slackConversationsHistoryTool:()=>dn,slackConversationsRepliesTool:()=>un,slackReactionsAddTool:()=>mn,slackToolsProject:()=>Xb});var Xb,Fi=h(()=>{"use strict";l();Ai();Ni();Oi();Ii();ji();Li();Ai();Ni();Oi();Ii();ji();Li();Xb={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:"slack"},tools:[cn,pn,mn,dn,un,fn]}});import{execFileSync as wC}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 xC(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 hC from"mysql2/promise";var ar,Wy=h(()=>{"use strict";l();sr();ar=class extends Qe{async getConnection(){return await hC.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 ie,Xe=h(()=>{"use strict";l();Fy();qy();Wy();ie=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new ir(e):e.startsWith("mysql://")?new ar(e):e.startsWith("sqlite://")?new dn(e.replace("sqlite://","")):new dn(e)}}});var lr,Uy=h(()=>{"use strict";l();jy();Xe();_();lr={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Iy,execute:async r=>{let e=r.db,t=r.sql,o=r.params||[];b(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let s=await ie.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 Gy,By=h(()=>{"use strict";l();Gy={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 cr,zy=h(()=>{"use strict";l();By();Xe();cr={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Gy,execute:async r=>{let e=r.db,t=r.table;try{let n=await ie.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var Hy,Ky=h(()=>{"use strict";l();Hy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var pr,Jy=h(()=>{"use strict";l();Ky();Xe();pr={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:Hy,execute:async r=>{let e=r.db;try{let o=await ie.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var Vy,Qy=h(()=>{"use strict";l();Vy={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to insert into"},data:{type:"object",description:"Key-value pairs of column names and values to insert"}},required:["db","table","data"]}});var mr,Xy=h(()=>{"use strict";l();Qy();Xe();mr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:Vy,execute:async r=>{let e=r.db,t=r.table,o=r.data;if(Object.keys(o).length===0)return"Error: No data provided to insert.";try{let n=Object.keys(o).join(", "),s=Object.keys(o).map(()=>"?").join(", "),i=Object.values(o),a=`INSERT INTO ${t} (${n}) VALUES (${s})`,p=await ie.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 Yy,Zy=h(()=>{"use strict";l();Yy={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 dr,eb=h(()=>{"use strict";l();Zy();Xe();dr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:Yy,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(d=>`${d} = ?`).join(", "),i=Object.values(o),a=`UPDATE ${t} SET ${s} WHERE ${n}`,p=await ie.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 tb,ob=h(()=>{"use strict";l();tb={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 ur,nb=h(()=>{"use strict";l();ob();Xe();ur={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:tb,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await ie.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 rb,sb=h(()=>{"use strict";l();rb={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 fr,ib=h(()=>{"use strict";l();sb();Xe();fr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:rb,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 ie.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 lb={};re(lb,{dbCountTool:()=>fr,dbDeleteTool:()=>ur,dbInsertTool:()=>mr,dbQueryTool:()=>lr,dbSchemaTool:()=>cr,dbTablesTool:()=>pr,dbToolsProject:()=>ab,dbUpdateTool:()=>dr});var ab,Ii=h(()=>{"use strict";l();Uy();zy();Jy();Xy();eb();nb();ib();ab={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:[lr,cr,pr,mr,dr,ur,fr],dependencies:{"better-sqlite3":"^11.3.0"}}});var cb,pb=h(()=>{"use strict";l();cb={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 yC}from"netlify";var Ye,gr=h(()=>{"use strict";l();Ye=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 yC(t)}}});var hr,mb=h(()=>{"use strict";l();pb();gr();_();hr={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:cb,execute:async(r,e)=>{let t=r.siteId,o=r.dir,n=r.message;b(`[cloud.deploy] execute siteId="${t}" dir="${o}" message="${n??"none"}"`);try{let i=await Ye.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 db,ub=h(()=>{"use strict";l();db={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 yr,fb=h(()=>{"use strict";l();ub();gr();yr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:db,execute:async(r,e)=>{let t=r.siteId,o=r.deployId;try{let s=await Ye.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 gb,hb=h(()=>{"use strict";l();gb={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 br,yb=h(()=>{"use strict";l();hb();gr();_();br={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:gb,execute:async(r,e)=>{let t=r.siteId,o=r.limit||5;b(`[cloud.list] execute siteId="${t}" limit=${o}`);try{let s=await Ye.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 Tb={};re(Tb,{cloudDeployTool:()=>hr,cloudListTool:()=>br,cloudStatusTool:()=>yr,cloudToolsProject:()=>bb});var bb,ji=h(()=>{"use strict";l();mb();fb();yb();bb={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:[hr,yr,br],dependencies:{netlify:"^13.1.20"}}});var wb,xb,vb,Cb,kb,Sb=h(()=>{"use strict";l();wb="slack.chat.postMessage",xb="Post Slack Message",vb="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.",Cb="slack",kb={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 Ce(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 gt=h(()=>{"use strict";l()});function bC(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}}async function ke(r,e,t){let o=await fetch(`https://slack.com/api/${r}`,{method:"POST",headers:bC(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 ht=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=Ce(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 ke("chat.postMessage",i,a),p=c.ts??"";return`Message posted. channel=${c.channel??t} ts=${p}`}var un,Li=h(()=>{"use strict";l();Sb();gt();ht();un={name:wb,displayName:xb,description:vb,parameters:kb,category:Cb,execute:TC}});var _b,Pb,Rb,$b,Eb,Db=h(()=>{"use strict";l();_b="slack.chat.postEphemeral",Pb="Post Ephemeral Slack Message",Rb="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.",$b="slack",Eb={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 wC(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=Ce(r.token,e?.config?.credentials),a={channel:t,user:o,text:n};return s&&(a.thread_ts=s),await ke("chat.postEphemeral",i,a),`Ephemeral message sent to user=${o} in channel=${t}.`}var fn,Fi=h(()=>{"use strict";l();Db();gt();ht();fn={name:_b,displayName:Pb,description:Rb,parameters:Eb,category:$b,execute:wC}});var Ab,Mb,Nb,Ob,Ib,jb=h(()=>{"use strict";l();Ab="slack.reactions.add",Mb="Add Slack Reaction",Nb="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.",Ob="slack",Ib={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 xC(r,e){let t=String(r.channel),o=String(r.timestamp),n=String(r.name),s=Ce(r.token,e?.config?.credentials);try{await ke("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 gn,qi=h(()=>{"use strict";l();jb();gt();ht();gn={name:Ab,displayName:Mb,description:Nb,parameters:Ib,category:Ob,execute:xC}});var Lb,Fb,qb,Wb,Ub,Gb=h(()=>{"use strict";l();Lb="slack.conversations.history",Fb="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.",Wb="slack",Ub={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 vC(r,e){let t=String(r.channel),o=typeof r.limit=="number"?Math.min(r.limit,100):10,n=Ce(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 ke("conversations.history",n,s)).messages??[];return a.length===0?"No messages found.":[...a].reverse().map(p=>{let d=p.user?`user:${p.user}`:p.bot_id?`bot:${p.bot_id}`:"unknown",m=p.reply_count?` [thread: ${p.reply_count} replies]`:"",g=(p.text??"").replace(/\n/g," ").slice(0,200);return`[${p.ts}] ${d}${m}: ${g}`}).join(`
319
+ `)}var hn,Wi=h(()=>{"use strict";l();Gb();gt();ht();hn={name:Lb,displayName:Fb,description:qb,parameters:Ub,category:Wb,execute:vC}});var Bb,zb,Hb,Kb,Jb,Vb=h(()=>{"use strict";l();Bb="slack.conversations.replies",zb="Get Slack Thread Replies",Hb="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.",Kb="slack",Jb={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 CC(r,e){let t=String(r.channel),o=String(r.ts),n=typeof r.limit=="number"?Math.min(r.limit,100):20,s=Ce(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 ke("conversations.replies",s,i)).messages??[];return c.length===0?"No replies found.":c.map((d,m)=>{let g=d.user?`user:${d.user}`:d.bot_id?`bot:${d.bot_id}`:"unknown",T=m===0?" [parent]":"",y=(d.text??"").replace(/\n/g," ").slice(0,200);return`[${d.ts}] ${g}${T}: ${y}`}).join(`
320
+ `)}var yn,Ui=h(()=>{"use strict";l();Vb();gt();ht();yn={name:Bb,displayName:zb,description:Hb,parameters:Jb,category:Kb,execute:CC}});var Qb,Xb,Yb,Zb,eT,tT=h(()=>{"use strict";l();Qb="slack.auth.test",Xb="Slack Auth Test",Yb="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.",Zb="slack",eT={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function kC(r,e){let t=Ce(r.token,e?.config?.credentials),o=await ke("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 bn,Gi=h(()=>{"use strict";l();tT();gt();ht();bn={name:Qb,displayName:Xb,description:Yb,parameters:eT,category:Zb,execute:kC}});var nT={};re(nT,{slackAuthTestTool:()=>bn,slackChatPostEphemeralTool:()=>fn,slackChatPostMessageTool:()=>un,slackConversationsHistoryTool:()=>hn,slackConversationsRepliesTool:()=>yn,slackReactionsAddTool:()=>gn,slackToolsProject:()=>oT});var oT,Bi=h(()=>{"use strict";l();Li();Fi();qi();Wi();Ui();Gi();Li();Fi();qi();Wi();Ui();Gi();oT={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:"slack"},tools:[un,fn,gn,hn,yn,bn]}});import{execFileSync as SC}from"child_process";function O(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 he(r,e,t=3e4){r.forEach((o,n)=>A(o,`kubectl argument #${n}`)),y(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return wC("kubectl",r,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return xC(o)}}function vC(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 Zb(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 Se,gr,hr,yr,br,Tr,wr,xr,vr,Cr,kr,Sr,eT=h(()=>{"use strict";l();S();Se="kubernetes";gr={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:Se,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter pods."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter pods.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the pod list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"If true, list pods across all namespaces.",default:!1}},required:[]},execute:async r=>{let e=["get","pods"],t=r.output;t?e.push("-o",t):e.push("-o","wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",A(r.namespace,"namespace"));let o=Zb(r.labelSelector)??r.labels;return o&&e.push("-l",A(o,"labels")),he(e)}},hr={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:Se,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to describe, such as pod, service, deployment."},name:{type:"string",description:"Resource name. Optional for cluster-wide descriptions."},namespace:{type:"string",description:"Namespace containing the resource."}},required:["resource"]},execute:async r=>{let t=["describe",A(r.resource,"resource")];return r.name&&t.push(A(r.name,"name")),r.namespace&&t.push("-n",A(r.namespace,"namespace")),he(t)}},yr={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:Se,parameters:{type:"object",properties:{podName:{type:"string",description:"The name of the pod to fetch logs from."},namespace:{type:"string",description:"Namespace of the pod."},container:{type:"string",description:"Container name inside the pod."},tailLines:{type:"number",description:"Number of log lines to show from the end.",default:100},since:{type:"string",description:"Return logs newer than a relative duration like 5m or 1h."}},required:["podName"]},execute:async r=>{let e=["logs",A(r.podName,"podName")];return r.container&&e.push("-c",A(r.container,"container")),r.namespace&&e.push("-n",A(r.namespace,"namespace")),typeof r.tailLines=="number"&&e.push("--tail",`${r.tailLines}`),r.since&&e.push("--since",A(r.since,"since")),he(e)}},br={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:Se,parameters:{type:"object",properties:{path:{type:"string",description:"Path to the manifest file to apply."},manifest:{type:"string",description:"Inline YAML manifest to apply if no path is provided."},namespace:{type:"string",description:"Namespace to apply the manifest into, if supported by the manifest."},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without applying changes.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will change cluster state by applying a Kubernetes manifest.",showArgs:["path","namespace"]},execute:async r=>{let e=r.path,t=r.manifest,o=["apply"];if(r.dryRun&&o.push("--dry-run=client"),o.push("-f"),e)return o.push(A(e,"path")),r.namespace&&o.push("-n",A(r.namespace,"namespace")),he(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("-"),he(o,t)}},Tr={name:"k8s.delete_resource",displayName:"Kubernetes Delete Resource",description:"Delete a Kubernetes resource by type and name, or delete resources from a manifest file.",category:Se,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to delete, such as pod, service, deployment."},name:{type:"string",description:"Name of the resource to delete."},namespace:{type:"string",description:"Namespace containing the resource."},path:{type:"string",description:"Path to a manifest file that contains the resources to delete."},force:{type:"boolean",description:"Force deletion of the resource.",default:!1},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without deleting resources.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will delete resources from the Kubernetes cluster.",showArgs:["resource","name","path"]},execute:async r=>{let e=r.path,t=r.resource,o=r.name;if(e){let s=["delete"];return r.dryRun&&s.push("--dry-run=client"),s.push("-f",A(e,"path")),r.namespace&&s.push("-n",A(r.namespace,"namespace")),he(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"),he(n)}},wr={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:Se,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},output:{type:"string",description:"Output format for the service list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List services across all namespaces.",default:!1}},required:[]},execute:async r=>{let e=["get","services"],t=r.output;return e.push("-o",t||"wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",A(r.namespace,"namespace")),he(e)}},xr={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:Se,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter deployments."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter deployments.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the deployment list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List deployments across all namespaces.",default:!1}},required:[]},execute:async r=>{let e=["get","deployments"],t=r.output;e.push("-o",t||"wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",A(r.namespace,"namespace"));let o=Zb(r.labelSelector)??r.labels;return o&&e.push("-l",A(o,"labels")),he(e)}},vr={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:Se,parameters:{type:"object",properties:{name:{type:"string",description:"ConfigMap name."},namespace:{type:"string",description:"Namespace containing the ConfigMap."},output:{type:"string",description:"Output format, such as yaml or json.",enum:["yaml","json"],default:"yaml"}},required:["name"]},execute:async r=>{let e=["get","configmap",A(r.name,"name"),"-o",r.output||"yaml"];return r.namespace&&e.push("-n",A(r.namespace,"namespace")),he(e)}},Cr={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:Se,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>he(["config","use-context",A(r.context,"context")])},kr={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:Se,parameters:{type:"object",properties:{output:{type:"string",description:"Output format for the namespace list.",enum:["wide","name","json","yaml"],default:"wide"}},required:[]},execute:async r=>he(["get","namespaces","-o",r.output||"wide"])},Sr={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:Se,parameters:{type:"object",properties:{name:{type:"string",description:"Deployment name to wait for."},namespace:{type:"string",description:"Namespace containing the deployment."},timeout:{type:"string",description:"Timeout duration, e.g. 300s or 5m.",default:"300s"}},required:["name"]},execute:async r=>{let e=r.timeout,t=["rollout","status",`deployment/${A(r.name,"name")}`,"--timeout",e||"300s"];return r.namespace&&t.push("-n",A(r.namespace,"namespace")),he(t,void 0,vC(e))}}});var oT={};te(oT,{k8sApplyManifestTool:()=>br,k8sDeleteResourceTool:()=>Tr,k8sDescribeTool:()=>hr,k8sGetConfigMapTool:()=>vr,k8sGetLogsTool:()=>yr,k8sGetNamespacesTool:()=>kr,k8sListDeploymentsTool:()=>xr,k8sListPodsTool:()=>gr,k8sListServicesTool:()=>wr,k8sSwitchContextTool:()=>Cr,k8sToolsProject:()=>tT,k8sWaitForDeploymentTool:()=>Sr});var tT,qi=h(()=>{"use strict";l();eT();tT={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:[gr,hr,yr,br,Tr,wr,xr,vr,Cr,kr,Sr]}});import{createRemoteJWKSet as qC,jwtVerify as WC}from"jose";function uT(r){switch(r.mode){case"static":return new Ji(r.tokens);case"jwt":return new Vi(r);case"custom":return{verifyAccessToken:r.verifyAccessToken}}}async function fT(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 Ji,Vi,gT=h(()=>{"use strict";l();Ji=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:[]}}},Vi=class{JWKS;audience;issuer;constructor(e){this.JWKS=qC(new URL(e.jwksUrl)),this.audience=e.audience,this.issuer=e.issuer}async verifyAccessToken(e){let{payload:t}=await WC(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 bT={};te(bT,{startMcpServer:()=>VC});import{createServer as UC}from"http";import{randomUUID as GC}from"crypto";import{Server as BC}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as zC}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as HC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{ListToolsRequestSchema as KC,CallToolRequestSchema as JC}from"@modelcontextprotocol/sdk/types.js";async function VC(r,e,t){let o=new BC({name:e.serverName??"Toolpack SDK",version:e.serverVersion??"2.0.0"},{capabilities:{tools:{}}});if(o.setRequestHandler(KC,async()=>{if(e.searchMode){let i=YC(r,e),a=Xe(),c=i.map(p=>{let m=yT(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,...hT(e)]}}return{tools:[...Qi(r,e.expose).map(i=>{let a=yT(i);return{name:i.name,description:i.description??"",inputSchema:i.parameters??{type:"object",properties:{}},...a!==void 0&&{annotations:a}}}),...hT(e)]}}),o.setRequestHandler(JC,async n=>{let{name:s,arguments:i}=n.params;if(e.searchMode&&yt(s)){if(!t)return Oe("tool.search is not available: searchFn was not provided to startMcpServer.",!0);try{let c=t(i??{});return Oe(c)}catch(c){let p=c instanceof Error?c.message:String(c);return Oe(`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 Oe(`Agent not found: ${c}`,!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 (${c}): ${d}`,!0)}}let a=QC(r,s,e.expose);if(!a)return Oe(`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 Oe(p)}catch(c){let p=c instanceof Error?c.message:String(c);return Oe(`Error executing ${s}: ${p}`,!0)}}),e.transport==="stdio"){let n=new zC;return await o.connect(n),{get toolCount(){return Qi(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 HC({sessionIdGenerator:()=>GC()}),i=e.auth?uT(e.auth):null,a=UC(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 fT(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 Qi(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 Qi(r,e){return e?e.categories?.length?r.getByCategories(e.categories):e.tools?.length?r.getByNames(e.tools):r.getEnabled():r.getEnabled()}function QC(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:XC(r,o,e)?o:void 0}function XC(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 hT(r){return(r.agents??[]).map(e=>({name:`agent.${e.name}`,description:e.description,inputSchema:e.inputSchema??{type:"object",properties:{}}}))}function YC(r,e){let t=r.getConfig().toolSearch;if(!t)return[];let o=r.getByNames(t.alwaysLoadedTools),n=r.getByCategories(t.alwaysLoadedCategories),s=new Set([Qe]),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 yT(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 TT=h(()=>{"use strict";l();S();gT();Ft()});l();l();var pk={image:{maxBytes:10485760},document:{maxBytes:10485760,maxPages:20}};ie();l();ie();import{EventEmitter as nw}from"events";l();ie();async function la(r,e={}){let{maxRetries:t=3,backoffMs:o=[1e4,3e4,6e4],isRetryable:n=i=>i instanceof se,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 se("Rate limit retries exhausted")}l();ie();var It=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`
325
+ ${t}`}function Te(r,e,t=3e4){r.forEach((o,n)=>O(o,`kubectl argument #${n}`)),b(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return SC("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 PC(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 rT(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])=>`${O(t,"label key")}=${O(o,"label value")}`).join(",")}var $e,Tr,wr,xr,vr,Cr,kr,Sr,_r,Pr,Rr,$r,sT=h(()=>{"use strict";l();_();$e="kubernetes";Tr={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",O(r.namespace,"namespace"));let o=rT(r.labelSelector)??r.labels;return o&&e.push("-l",O(o,"labels")),Te(e)}},wr={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",O(r.resource,"resource")];return r.name&&t.push(O(r.name,"name")),r.namespace&&t.push("-n",O(r.namespace,"namespace")),Te(t)}},xr={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",O(r.podName,"podName")];return r.container&&e.push("-c",O(r.container,"container")),r.namespace&&e.push("-n",O(r.namespace,"namespace")),typeof r.tailLines=="number"&&e.push("--tail",`${r.tailLines}`),r.since&&e.push("--since",O(r.since,"since")),Te(e)}},vr={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(O(e,"path")),r.namespace&&o.push("-n",O(r.namespace,"namespace")),Te(o);if(!t)throw new Error("Either path or manifest is required to apply a Kubernetes manifest.");return r.namespace&&o.push("-n",O(r.namespace,"namespace")),o.push("-"),Te(o,t)}},Cr={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",O(e,"path")),r.namespace&&s.push("-n",O(r.namespace,"namespace")),Te(s)}if(!t||!o)throw new Error("resource and name are required unless a manifest path is provided.");let n=["delete",O(t,"resource"),O(o,"name")];return r.namespace&&n.push("-n",O(r.namespace,"namespace")),r.force&&n.push("--force","--grace-period=0"),r.dryRun&&n.push("--dry-run=client"),Te(n)}},kr={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",O(r.namespace,"namespace")),Te(e)}},Sr={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",O(r.namespace,"namespace"));let o=rT(r.labelSelector)??r.labels;return o&&e.push("-l",O(o,"labels")),Te(e)}},_r={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",O(r.name,"name"),"-o",r.output||"yaml"];return r.namespace&&e.push("-n",O(r.namespace,"namespace")),Te(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:$e,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>Te(["config","use-context",O(r.context,"context")])},Rr={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=>Te(["get","namespaces","-o",r.output||"wide"])},$r={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/${O(r.name,"name")}`,"--timeout",e||"300s"];return r.namespace&&t.push("-n",O(r.namespace,"namespace")),Te(t,void 0,PC(e))}}});var aT={};re(aT,{k8sApplyManifestTool:()=>vr,k8sDeleteResourceTool:()=>Cr,k8sDescribeTool:()=>wr,k8sGetConfigMapTool:()=>_r,k8sGetLogsTool:()=>xr,k8sGetNamespacesTool:()=>Rr,k8sListDeploymentsTool:()=>Sr,k8sListPodsTool:()=>Tr,k8sListServicesTool:()=>kr,k8sSwitchContextTool:()=>Pr,k8sToolsProject:()=>iT,k8sWaitForDeploymentTool:()=>$r});var iT,zi=h(()=>{"use strict";l();sT();iT={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:[Tr,wr,xr,vr,Cr,kr,Sr,_r,Pr,Rr,$r]}});import{createRemoteJWKSet as zC,jwtVerify as HC}from"jose";function bT(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 TT(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(d=>!c.has(d));if(p.length>0)return e.writeHead(403).end(`Missing required scopes: ${p.join(", ")}`),!1}return r.auth=i,!0}var Zi,ea,wT=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=zC(new URL(e.jwksUrl)),this.audience=e.audience,this.issuer=e.issuer}async verifyAccessToken(e){let{payload:t}=await HC(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 CT={};re(CT,{startMcpServer:()=>ek});import{createServer as KC}from"http";import{randomUUID as JC}from"crypto";import{Server as VC}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as QC}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as XC}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{ListToolsRequestSchema as YC,CallToolRequestSchema as ZC}from"@modelcontextprotocol/sdk/types.js";async function ek(r,e,t){let o=new VC({name:e.serverName??"Toolpack SDK",version:e.serverVersion??"2.0.0"},{capabilities:{tools:{}}});if(o.setRequestHandler(YC,async()=>{if(e.searchMode){let i=nk(r,e),a=nt(),c=i.map(p=>{let d=vT(p);return{name:p.name,description:p.description??"",inputSchema:p.parameters??{type:"object",properties:{}},...d!==void 0&&{annotations:d}}});return{tools:[{name:a.name,description:a.description??"",inputSchema:a.parameters,annotations:{readOnlyHint:!0}},...c,...xT(e)]}}return{tools:[...ta(r,e.expose).map(i=>{let a=vT(i);return{name:i.name,description:i.description??"",inputSchema:i.parameters??{type:"object",properties:{}},...a!==void 0&&{annotations:a}}}),...xT(e)]}}),o.setRequestHandler(ZC,async n=>{let{name:s,arguments:i}=n.params;if(e.searchMode&&vt(s)){if(!t)return Fe("tool.search is not available: searchFn was not provided to startMcpServer.",!0);try{let c=t(i??{});return Fe(c)}catch(c){let p=c instanceof Error?c.message:String(c);return Fe(`tool.search error: ${p}`,!0)}}if(s.startsWith("agent.")){let c=s.slice(6),p=(e.agents??[]).find(d=>d.name===c);if(!p)return Fe(`Agent not found: ${c}`,!0);try{let d=await p.invoke(i??{});return Fe(d)}catch(d){let m=d instanceof Error?d.message:String(d);return Fe(`Agent error (${c}): ${m}`,!0)}}let a=tk(r,s,e.expose);if(!a)return Fe(`Tool not found: ${s}`,!0);try{let c={workspaceRoot:process.cwd(),config:r.getConfig().additionalConfigurations??{},log:d=>S(`[MCP Tool] ${d}`),processRegistry:r.runtimeContext?.processRegistry,githubTokenStore:r.runtimeContext?.githubTokenStore},p=await a.execute(i??{},c);return Fe(p)}catch(c){let p=c instanceof Error?c.message:String(c);return Fe(`Error executing ${s}: ${p}`,!0)}}),e.transport==="stdio"){let n=new QC;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||S("[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 XC({sessionIdGenerator:()=>JC()}),i=e.auth?bT(e.auth):null,a=KC(async(p,d)=>{if(e.auth?.mode==="jwt"&&e.serverUrl&&p.url==="/.well-known/oauth-protected-resource"){let m={resource:e.serverUrl};e.auth.issuer&&(m.authorization_servers=[e.auth.issuer]),d.writeHead(200,{"Content-Type":"application/json"}).end(JSON.stringify(m));return}i&&!await TT(p,d,e.auth,i).catch(g=>(S(`[MCP Server] Auth error: ${g instanceof Error?g.message:String(g)}`),d.headersSent||d.writeHead(500).end("Internal Server Error"),!1))||s.handleRequest(p,d).catch(m=>{S(`[MCP Server] HTTP request handler error: ${m instanceof Error?m.message:String(m)}`),d.headersSent||d.writeHead(500).end("Internal Server Error")})});await o.connect(s);try{await new Promise((p,d)=>{let m=g=>{d(g.code==="EADDRINUSE"?new Error(`MCP HTTP server failed to start: port ${n} is already in use.`):g)};a.once("error",m),a.listen(n,()=>{a.off("error",m),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,d)=>{a.close(m=>m?d(m):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 tk(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:ok(r,o,e)?o:void 0}function ok(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 xT(r){return(r.agents??[]).map(e=>({name:`agent.${e.name}`,description:e.description,inputSchema:e.inputSchema??{type:"object",properties:{}}}))}function nk(r,e){let t=r.getConfig().toolSearch;if(!t)return[];let o=r.getByNames(t.alwaysLoadedTools),n=r.getByCategories(t.alwaysLoadedCategories),s=new Set([ot]),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 vT(r){if(r.annotations)return r.annotations;if(r.confirmation)return{destructiveHint:!0}}function Fe(r,e=!1){return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r,null,2)}],isError:e}}var kT=h(()=>{"use strict";l();_();wT();Gt()});l();l();var gk={image:{maxBytes:10485760},document:{maxBytes:10485760,maxPages:20}};pe();l();pe();import{EventEmitter as lw}from"events";l();pe();async function ua(r,e={}){let{maxRetries:t=3,backoffMs:o=[1e4,3e4,6e4],isRetryable:n=i=>i instanceof ce,onRetry:s}=e;for(let i=0;i<=t;i++)try{return await r()}catch(a){if(n(a)&&i<t){let 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 ce("Rate limit retries exhausted")}l();pe();var qt=class extends I{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 jt=class extends N{constructor(t,o,n,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=n;this.failureReason=s;this.summaryAttempt=i;this.name="SummarizationError"}conversationId;messageCount;failureReason;summaryAttempt;isRetryable(){return this.failureReason==="provider_error"||this.failureReason==="insufficient_tokens"}getSuggestedRecovery(){switch(this.failureReason){case"provider_error":return"Retry the summarization request or switch to a different summarizer model";case"invalid_response":return"Review the summarizer prompt or use a different model";case"insufficient_tokens":return"Reduce the number of messages to summarize or increase the summary token budget";case"invalid_quality":return"Adjust summarization parameters or use a more capable model";default:return"Manual intervention required"}}getDetailedReport(){let t=`
336
+ `.trim()}};var Wt=class extends I{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()}};l();var Lr=null;async function OT(){if(!Lr)try{Lr=await import("js-tiktoken")}catch{}return Lr}var ca={"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},IT=2;async function jT(r,e){try{let t=await OT();if(!t)return je(r);let o=t.encoding_for_model(e),n=0,s=ca[e]??ca.__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+=IT,n}catch{return je(r)}}async function LT(r,e){try{let t=je(r);return Math.ceil(t*1.1)}catch{return je(r)}}async function FT(r,e){try{let t=je(r);return Math.ceil(t*1.05)}catch{return je(r)}}async function qT(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 pa(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?jT(r,e):o==="anthropic"||o==="claude"?LT(r,e):o==="gemini"||o==="google"?FT(r,e):o==="ollama"?qT(r,e):je(r)}function Ck(r,e,t){let o=e-t;return r>o}function kk(r,e){return Math.round(r/e*100)}function ma(r,e=1.15){return Math.ceil(r*e)}l();function da(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=Fr(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+=Fr(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 _k(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 Ur=null;async function qT(){if(!Ur)try{Ur=await import("js-tiktoken")}catch{}return Ur}var fa={"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},WT=2;async function UT(r,e){try{let t=await qT();if(!t)return Ge(r);let o=t.encoding_for_model(e),n=0,s=fa[e]??fa.__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+=WT,n}catch{return Ge(r)}}async function GT(r,e){try{let t=Ge(r);return Math.ceil(t*1.1)}catch{return Ge(r)}}async function BT(r,e){try{let t=Ge(r);return Math.ceil(t*1.05)}catch{return Ge(r)}}async function zT(r,e){let t=Ge(r);return Math.ceil(t*1.05)}function Ge(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 ga(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?UT(r,e):o==="anthropic"||o==="claude"?GT(r,e):o==="gemini"||o==="google"?BT(r,e):o==="ollama"?zT(r,e):Ge(r)}function Rk(r,e,t){let o=e-t;return r>o}function $k(r,e){return Math.round(r/e*100)}function ha(r,e=1.15){return Math.ceil(r*e)}l();function ya(r,e,t=!0){let o=r.length,n=[],s=0,i=[];r.forEach((p,d)=>{t&&p.role==="system"||p.role!=="tool"&&i.push({index:d,message:p})});for(let{message:p}of i){if(s>=e)break;let d=Gr(p);if(s+=d,n.push(p),p.role==="assistant"&&p.tool_calls?.length){let m=new Set(p.tool_calls.map(g=>g.id));for(let g of r)g.role==="tool"&&g.tool_call_id&&m.has(g.tool_call_id)&&(s+=Gr(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 Ak(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,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}
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 d=p.substring(0,c),m=Math.ceil((p.length-c)/4);i.push({type:"text",text:`${d}
351
351
 
352
- [...truncated ${d} tokens]`});break}}return{...r,content:i.length>0?i:r.content}}return r}function Fr(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 Rk(r){let e={system:[],user:[],assistant:[],tool:[]};return r.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function $k(r){let e=0,t={},o=0;for(let n of r){let s=Fr(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();ie();function qr(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 WT(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`:""}).
352
+ [...truncated ${m} tokens]`});break}}return{...r,content:i.length>0?i:r.content}}return r}function Gr(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 Nk(r){let e=0,t={},o=0;for(let n of r){let s=Gr(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();pe();function Br(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 HT(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((c,p)=>{let m=qr(c);return`[Message ${p+1}] ${c.role.toUpperCase()}: ${m.substring(0,200)}${m.length>200?"...":""}`}).join(`
364
+ ${r.map((c,p)=>{let d=Br(c);return`[Message ${p+1}] ${c.role.toUpperCase()}: ${d.substring(0,200)}${d.length>200?"...":""}`}).join(`
365
365
  `)}
366
366
  ---
367
367
 
368
- SUMMARY:`}function Wr(r,e){return{role:"system",content:`[Context Summary]
368
+ SUMMARY:`}function zr(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 Ak(r){let e=new Set,t=[],o=[],n="";for(let s of r)if(s.role==="user"){let i=qr(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=qr(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 UT(r){return Math.ceil(r.length/4)}function ua(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 fa(r,e){let t=WT(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=Br(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=Br(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 KT(r){return Math.ceil(r.length/4)}function ba(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 Ta(r,e){let t=HT(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 ga(r,e,t){let o=UT(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function Nk(r,e,t){let o=[...r];return o.push(Wr(e.summary,e.messageCount)),o.push(...t),o}function Ok(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=KT(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function Fk(r,e,t){let o=[...r];return o.push(zr(e.summary,e.messageCount)),o.push(...t),o}function qk(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,40 +395,40 @@ Message Count:
395
395
 
396
396
  Summary Preview:
397
397
  ${r.summary.substring(0,300)}${r.summary.length>300?"...":""}
398
- `.trim()}function Ik(r){if(r.length===0)throw new N("Cannot merge empty summarization results","CONTEXT_WINDOW_ERROR");return{summary:r.map(t=>`[Round ${r.indexOf(t)+1}] ${t.summary}`).join(`
398
+ `.trim()}function Wk(r){if(r.length===0)throw new I("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}}l();var Ur=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 T=d.pruneCount+d.summarizationCount;return g.pruneCount+g.summarizationCount-T}).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 ha(r){return new Ur(r)}l();Ft();var qt=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,i=t.getCategories().filter(p=>p!=="meta");n.push(Xe(i.length?i:void 0)),s.add(Qe);let a=o.toolSearch?.alwaysLoadedTools??[];for(let p of a){let m=t.get(p);m&&!s.has(p)&&(n.push(this.toSchema(m)),s.add(p))}let c=o.toolSearch?.alwaysLoadedCategories??[];for(let p of c)for(let m of t.getByCategory(p))s.has(m.name)||(n.push(this.toSchema(m)),s.add(m.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let p=ht.fromMessages(e);this.discoveryCache.merge(p);let m=this.discoveryCache.getDiscoveredTools();for(let d of m){let g=t.get(d);g&&!s.has(d)&&g.cacheable!==!1&&(n.push(this.toSchema(g)),s.add(d))}}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 zT={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},oe={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:zT};Ft();l();function xa(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 Hr=class{states=new Map;config;maxTokens=1e5;constructor(e){this.config=e}getOrCreateState(e){return this.states.has(e)||this.states.set(e,{conversationId:e,estimatedTokens:0,lastUpdated:Date.now(),pruneCount:0,lastPrunedAt:void 0,warningsSent:0,summarizationCount:0}),this.states.get(e)}updateTokenCount(e,t){let o=this.getOrCreateState(e);return o.estimatedTokens=t,o.lastUpdated=Date.now(),o}recordPruneOperation(e,t){let o=this.getOrCreateState(e);return o.pruneCount++,o.lastPrunedAt=Date.now(),o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}recordWarning(e){let t=this.getOrCreateState(e);return t.warningsSent++,t.lastUpdated=Date.now(),t}recordSummarization(e,t){let o=this.getOrCreateState(e);return o.summarizationCount++,o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}getState(e){return this.states.get(e)}getAllStates(){return Array.from(this.states.values())}deleteState(e){return this.states.delete(e)}clearAllStates(){this.states.clear()}getStatistics(e){let t=this.states.get(e);if(!t)return null;let o=this.config.pruneThreshold||1e5,n=Math.round(t.estimatedTokens/o*100);return{conversationId:e,currentTokens:t.estimatedTokens,pruneCount:t.pruneCount,summarizationCount:t.summarizationCount,warningsSent:t.warningsSent,lastActivity:new Date(t.lastUpdated),contextWindowPercentage:n}}getExceedingThreshold(e){let t=e||this.maxTokens*(this.config.pruneThreshold||85)/100;return Array.from(this.states.values()).filter(o=>o.estimatedTokens>t)}getAtRiskConversations(e=80){let t=this.maxTokens,o=t*e/100;return Array.from(this.states.values()).filter(n=>n.estimatedTokens>o&&n.estimatedTokens<=t)}generateReport(){let e=this.getAllStates();if(e.length===0)return"No conversations tracked yet.";let t=this.config.pruneThreshold||1e5,o=["Context Window State Report","==========================",`Report Generated: ${new Date().toISOString()}`,`Context Window Limit: ${t} tokens`,`Total Conversations: ${e.length}`,""],n=e.reduce((m,g)=>m+g.estimatedTokens,0),s=e.reduce((m,g)=>m+g.pruneCount,0),i=e.reduce((m,g)=>m+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(m=>{let g=Math.round(m.estimatedTokens/t*100);o.push(`- ${m.conversationId}: ${m.estimatedTokens}/${t} tokens (${g}%)`)}),o.push(""));let p=this.getExceedingThreshold();return p.length>0&&(o.push(`Exceeded Conversations: ${p.length}`),p.forEach(m=>{let g=m.estimatedTokens-t;o.push(`- ${m.conversationId}: ${m.estimatedTokens}/${t} tokens (+${g} over)`)}),o.push("")),o.push("Most Active Conversations (by operations):"),[...e].sort((m,g)=>{let T=m.pruneCount+m.summarizationCount;return g.pruneCount+g.summarizationCount-T}).slice(0,5).forEach(m=>{let g=m.pruneCount+m.summarizationCount;o.push(`- ${m.conversationId}: ${m.pruneCount} prunes, ${m.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 xa(r){return new Hr(r)}l();Gt();var Bt=class{discoveryCache=new xt;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,i=t.getCategories().filter(p=>p!=="meta");n.push(nt(i.length?i:void 0)),s.add(ot);let a=o.toolSearch?.alwaysLoadedTools??[];for(let p of a){let d=t.get(p);d&&!s.has(p)&&(n.push(this.toSchema(d)),s.add(p))}let c=o.toolSearch?.alwaysLoadedCategories??[];for(let p of c)for(let d of t.getByCategory(p))s.has(d.name)||(n.push(this.toSchema(d)),s.add(d.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let p=xt.fromMessages(e);this.discoveryCache.merge(p);let d=this.discoveryCache.getDiscoveredTools();for(let m of d){let g=t.get(m);g&&!s.has(m)&&g.cacheable!==!1&&(n.push(this.toSchema(g)),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 QT={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},se={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:QT};Gt();l();function _a(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`}l();var bt=class{analyticalPatterns=[/\b(analyze|find|search|check|list|show)\b/i,/\b(biggest|largest|smallest|most|least|all|every|count)\b/i,/\b(explain|understand|review|audit|inspect|examine)\b/i,/\b(compare|difference|similar|match|pattern)\b/i,/\b(what|where|how many|which|who|when|why|how)\b/i,/\?$/];actionPatterns=[/\b(create|write|update|modify|edit|patch|delete|remove|rename|move|copy)\b/i,/\b(run|execute|start|stop|restart|deploy|install|build)\b/i,/\b(fix|refactor|implement|add|change|replace|insert)\b/i,/\b(make|do|set|configure|setup|initialize)\b/i];classify(e){if(!e||e.trim().length===0)return{type:"conversational",confidence:0};let t=e.toLowerCase(),o=this.analyticalPatterns.filter(a=>a.test(t)).length,n=this.actionPatterns.filter(a=>a.test(t)).length,s=o/this.analyticalPatterns.length,i=n/this.actionPatterns.length;if(o>n&&o>0){let a=Math.min(s,1);return n>0&&(a=Math.min(a,.5)),{type:"analytical",confidence:a,reasoning:`Matched ${o} analytical patterns${n>0?`, ${n} action patterns (capped confidence)`:""}`}}else return n>o&&n>0?{type:"action",confidence:Math.min(i,1),reasoning:`Matched ${n} action patterns`}:o===n&&o>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${o} analytical, ${n} action patterns)`}:{type:"conversational",confidence:.3,reasoning:"No strong analytical or action patterns detected"}}getToolRoundsAdjustment(e,t){return e.type==="analytical"&&e.confidence>.6?Math.min(t+3,10):(e.type==="action"&&e.confidence>.6,t)}};l();var wn=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let n=e[o],s=[],i=JSON.stringify(n.arguments).toLowerCase();for(let a=0;a<o;a++){let c=e[a];this.hasDependency(n,c,i)&&s.push(c.id)}t.push({toolCallId:n.id,dependsOn:s})}return t}hasDependency(e,t,o){if(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&o.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&o.includes(t.arguments.url.toLowerCase()))return!0;let s=["github.pr.files.list","github.pr.diff.get","github.contents.getText"];if(["github.pr.reviews.submit","github.pr.reviewComments.reply"].includes(e.name)&&s.includes(t.name)||e.name==="github.contents.getText"&&t.name==="github.pr.files.list"||e.name==="github.pr.reviewThreads.resolve"&&t.name==="github.pr.reviewThreads.list")return!0;let a=["slack.conversations.history","slack.conversations.replies"];return!!(["slack.chat.postMessage","slack.chat.postEphemeral"].includes(e.name)&&a.includes(t.name)||e.name==="slack.reactions.add"&&a.includes(t.name))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let n=this.analyzeDependencies(e),s=new Map,i=new Set;for(;i.size<e.length;){let a=[];for(let p of e){if(i.has(p.id))continue;(n.find(g=>g.toolCallId===p.id)?.dependsOn.every(g=>i.has(g))??!0)&&a.push(p)}if(a.length===0){let p=e.filter(m=>!i.has(m.id));throw new Error(`Circular dependency detected in tool calls: ${p.map(m=>m.name).join(", ")}`)}let c=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:m}of c)s.set(p,m),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let n=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 Ye(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 XT,readdir as YT}from"fs/promises";import{resolve as ZT,join as Hr,extname as ew}from"path";l();function Pa(r){return r.trim()}var tw=".toolpack/rules",ow=3e4,wt=class{constructor(e=ow){this.cacheTtlMs=e}cacheTtlMs;modeCache=new Map;async loadForMode(e,t){let o=t??tw,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(Hr(o,"__global__"),i),e&&await this.collectFromFolder(Hr(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=Pa(d);g&&c.push(g)}let p=c.length===0?"":`<rules>
408
+ - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}l();var Ct=class{analyticalPatterns=[/\b(analyze|find|search|check|list|show)\b/i,/\b(biggest|largest|smallest|most|least|all|every|count)\b/i,/\b(explain|understand|review|audit|inspect|examine)\b/i,/\b(compare|difference|similar|match|pattern)\b/i,/\b(what|where|how many|which|who|when|why|how)\b/i,/\?$/];actionPatterns=[/\b(create|write|update|modify|edit|patch|delete|remove|rename|move|copy)\b/i,/\b(run|execute|start|stop|restart|deploy|install|build)\b/i,/\b(fix|refactor|implement|add|change|replace|insert)\b/i,/\b(make|do|set|configure|setup|initialize)\b/i];classify(e){if(!e||e.trim().length===0)return{type:"conversational",confidence:0};let t=e.toLowerCase(),o=this.analyticalPatterns.filter(a=>a.test(t)).length,n=this.actionPatterns.filter(a=>a.test(t)).length,s=o/this.analyticalPatterns.length,i=n/this.actionPatterns.length;if(o>n&&o>0){let a=Math.min(s,1);return n>0&&(a=Math.min(a,.5)),{type:"analytical",confidence:a,reasoning:`Matched ${o} analytical patterns${n>0?`, ${n} action patterns (capped confidence)`:""}`}}else return n>o&&n>0?{type:"action",confidence:Math.min(i,1),reasoning:`Matched ${n} action patterns`}:o===n&&o>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${o} analytical, ${n} action patterns)`}:{type:"conversational",confidence:.3,reasoning:"No strong analytical or action patterns detected"}}getToolRoundsAdjustment(e,t){return e.type==="analytical"&&e.confidence>.6?Math.min(t+3,10):(e.type==="action"&&e.confidence>.6,t)}};l();var kn=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(d=>!i.has(d.id));throw new Error(`Circular dependency detected in tool calls: ${p.map(d=>d.name).join(", ")}`)}let c=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:d}of c)s.set(p,d),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 rt(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""}_();l();l();import{readFile as ow,readdir as nw}from"fs/promises";import{resolve as rw,join as Xr,extname as sw}from"path";l();function Da(r){return r.trim()}var iw=".toolpack/rules",aw=3e4,kt=class{constructor(e=aw){this.cacheTtlMs=e}cacheTtlMs;modeCache=new Map;async loadForMode(e,t){let o=t??iw,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 d of i){let m=await this.readFile(d,a);if(!m)continue;let g=Da(m);g&&c.push(g)}let p=c.length===0?"":`<rules>
410
410
  ${c.join(`
411
411
 
412
412
  `)}
413
- </rules>`;return this.modeCache.set(n,{value:p,cachedAt:Date.now()}),p}clearCache(){this.modeCache.clear()}async collectFromFolder(e,t){let o=ZT(e);try{await this.collectRecursive(o,t)}catch{}}async collectRecursive(e,t){let o=await YT(e,{withFileTypes:!0});for(let n of o){let s=Hr(e,n.name);n.isDirectory()?await this.collectRecursive(s,t):n.isFile()&&ew(n.name)===".md"&&t.add(s)}}async readFile(e,t){if(t.has(e))return t.get(e);try{let o=await XT(e,"utf-8");return t.set(e,o),o}catch{return""}}};function xn(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 _a(r){let e=Ye(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 Ra(r){let e=Ye(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 vn=class extends nw{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||oe,this.toolRouter=new qt,this.bm25Engine=new Lt,this.queryClassifier=new bt,this.toolOrchestrator=new wn,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??oe.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.hitlConfig=e.hitlConfig,this.onToolConfirm=e.onToolConfirm,this.conversationId=e.conversationId,this.contextWindowConfig=e.contextWindowConfig,this.providerModelCache=new Map,this.ruleLoader=new wt,this.contextWindowConfig&&this.contextWindowConfig.enabled!==!1&&(this.contextWindowStateManager=ha(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:pa(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=da(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=fa(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 jt("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let d=await this.countRequestTokens({...e,messages:a},t,c),g=ga(m.content,a,d),T=ua(g);if(!T.valid)throw new jt(`Summarization result is invalid: ${T.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",m.content);let b=Wr(g.summary,a.length),w=[...n,b,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),g.tokensSaved),{...e,messages:w}}async enforceContextWindow(e,t){if(!this.contextWindowConfig||this.contextWindowConfig.enabled===!1)return e;let o=await this.pruneToMaxMessageHistory(e),n=await this.getModelInfo(t,o.model),s=n?.contextWindow??1e5,i=o.max_tokens??n?.maxOutputTokens??1024,a=this.contextWindowConfig.outputTokenBuffer??1.15,c=ma(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 T=this.contextWindowConfig.strategy??"prune";if(T==="fail"&&g>p)throw new It("Context window exceeded by request messages",this.getConversationId(),g,p,T);if(T==="summarize")try{let w=await this.summarizeConversation(o,t);if(await this.countRequestTokens(w,t,w.model)<=p)return w;o=await this.pruneConversation(w,t,p)}catch{o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let b=await this.countRequestTokens(o,t,o.model);if(b>p&&T==="fail")throw new It("Context window exceeded after attempted cleanup",this.getConversationId(),b,p,T);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",T=(m.tools?.length||0)>0,b=m.tool_choice!=null,w=_a(m.messages),k=Ra(m.messages);!b&&T&&(g==="required"||g==="required_for_actions"&&w)&&(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=${w} autoExecute=${i.enabled&&i.autoExecute}`),xn(n,m.messages);let E=ee=>la(()=>o.generate(ee),{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 ee=Ye(m.messages),F=this.queryClassifier.classify(ee),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 Pe=0,Q=[...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&&Pe<q;){if(e.signal?.aborted){P(`[AIClient][${n}] generate() aborted by signal`);break}Pe++,P(`[AIClient][${n}] generate() tool round ${Pe}/${q} tool_calls=${$.tool_calls.length}`),Q.push({role:"assistant",content:$.content||"",tool_calls:$.tool_calls.map(H=>({id:H.id,type:"function",function:{name:H.name,arguments:JSON.stringify(H.arguments)}}))});let dt=this.toolOrchestrator.shouldUseParallelExecution($.tool_calls),ut=3,ce=$.tool_calls,De=$.tool_calls.filter(H=>H.name==="web.fetch");if(De.length>ut){P(`[AIClient][${n}] Limiting web.fetch calls from ${De.length} \u2192 ${ut} to prevent context overflow`);let H=De.slice(0,ut);ce=[...$.tool_calls.filter(ue=>ue.name!=="web.fetch"),...H];let z=De.slice(ut);for(let ue of z)Q.push({role:"tool",tool_call_id:ue.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let re=5e4,de=0;if(dt){P(`[AIClient][${n}] Using parallel execution for ${ce.length} tools`);let H;try{H=await this.toolOrchestrator.executeWithDependencies(ce,W=>this.executeTool(W,d,s,Pe),5)}catch(W){pe(`[AIClient][${n}] Parallel tool execution failed: ${W.message}`),H=new Map(ce.map(z=>[z.id,JSON.stringify({error:W.message??"Tool execution failed"})]))}for(let W of ce){let z=H.get(W.id)??JSON.stringify({error:"Tool execution result missing"}),ue=typeof z=="string"?z:JSON.stringify(z),Me=re-de,X=ue.startsWith("data:image/"),R;X?R=ue:de+ue.length>re?(O(`[AIClient][${n}] Tool output budget exceeded (${re} chars)`),R=this.budgetTruncate(ue,Me)):typeof z=="string"&&z.length>this.toolResultMaxChars?R=`${z.slice(0,this.toolResultMaxChars)}
414
- [TRUNCATED tool result: ${z.length} chars]`:R=ue;let K=typeof R=="string"?R:JSON.stringify(R);X||(de+=K.length),Q.push({role:"tool",tool_call_id:W.id,content:R})}y(`[AIClient][${n}] Round tool output size: ${de} chars (budget: ${re})`)}else{P(`[AIClient][${n}] Using sequential execution for ${ce.length} tools`);for(let H of ce){let W;try{W=await this.executeTool(H,d,s,Pe)}catch(K){W=JSON.stringify({error:K.message??"Tool execution failed"})}let z=typeof W=="string"?W:JSON.stringify(W),ue=re-de,Me=z.startsWith("data:image/"),X;Me?X=z:de+z.length>re?(O(`[AIClient][${n}] Tool output budget exceeded (${re} chars)`),X=this.budgetTruncate(z,ue)):typeof W=="string"&&W.length>this.toolResultMaxChars?X=`${W.slice(0,this.toolResultMaxChars)}
415
- [TRUNCATED tool result: ${W.length} chars]`:X=z;let R=typeof X=="string"?X:JSON.stringify(X);Me||(de+=R.length),Q.push({role:"tool",tool_call_id:H.id,content:X})}y(`[AIClient][${n}] Round tool output size: ${de} chars (budget: ${re})`)}let ft={...m,messages:Q,__toolpack_request_id:n,...C?{response_format:C}:{}},xe=this.stripRequestTools((await this.enrichRequestWithTools(ft,s)).request);xe=await this.enforceContextWindow(xe,o),xe.tool_choice==="required"&&(xe.tool_choice=k?"none":"auto",P(`[AIClient][${n}] generate() followup tool_choice override required->${xe.tool_choice}`)),Tt("debug")&&(y(`[AIClient][${n}] generate() followup request messages=${Q.length}`),xn(n,Q)),$=await E(xe),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",T=(m.tools?.length||0)>0,b=m.tool_choice!=null,w=_a(m.messages),k=Ra(m.messages);!b&&T&&(g==="required"||g==="required_for_actions"&&w)&&(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=${w} autoExecute=${a.enabled&&a.autoExecute}`),xn(n,m.messages),!a.autoExecute||!this.toolRegistry&&d.size===0&&(i?.customTools?.length??0)===0){yield*o.stream(_);return}let E=[...m.messages],$=0,ee=Ye(m.messages),F=this.queryClassifier.classify(ee),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 Pe="",Q=[];$++,P(`[AIClient][${n}] stream() round_start ${$}/${q}`);let dt=null,ut={...m,messages:E,...C?{response_format:C}:{}},ce=this.stripRequestTools((await this.enrichRequestWithTools(ut,i)).request);ce=await this.enforceContextWindow(ce,o),$>1&&ce.tool_choice==="required"&&(ce.tool_choice=k?"none":"auto",P(`[AIClient][${n}] stream() round_${$} tool_choice override required->${ce.tool_choice}`));for await(let R of o.stream(ce)){if(e.signal?.aborted){P(`[AIClient][${n}] stream() aborted by signal during chunk processing`);return}R.tool_calls&&R.tool_calls.length>0&&(Q.push(...R.tool_calls),y(`[AIClient][${n}] stream() tool_calls_chunk count=${R.tool_calls.length} names=${R.tool_calls.map(K=>K.name).join(", ")}`),yield R),R.delta&&(Pe+=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=${Pe.length} tool_calls_total=${Q.length} content_preview=${D(Pe,200)}`),Q.length===0)break;P(`[AIClient][${n}] stream() received ${Q.length} tool call(s): ${Q.map(R=>R.name).join(", ")}`),P(`[AIClient][${n}] stream() tool round ${$}/${q}`),E.push({role:"assistant",content:Pe||"",tool_calls:Q.map(R=>({id:R.id,type:"function",function:{name:R.name,arguments:JSON.stringify(R.arguments)}}))});let De=3,re=Q,de=Q.filter(R=>R.name==="web.fetch");if(de.length>De){P(`[AIClient][${n}] Limiting web.fetch calls from ${de.length} \u2192 ${De} to prevent context overflow`);let R=de.slice(0,De);re=[...Q.filter(Ot=>Ot.name!=="web.fetch"),...R];let ve=de.slice(De);for(let Ot of ve)E.push({role:"tool",tool_call_id:Ot.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ft=5e4,xe=0,H=[],W=!1,z=setInterval(()=>{W||H.push({delta:""})},500),ue=Date.now(),Me,X;try{if(re.length>=2)P(`[AIClient][${n}] stream() using parallel execution for ${re.length} tools`),X=new Map,Me=await this.toolOrchestrator.executeWithDependencies(re,async R=>{let K=Date.now(),ve=await this.executeTool(R,d,i,$);return X.set(R.id,Date.now()-K),ve},5);else{P(`[AIClient][${n}] stream() executing single tool sequentially`),X=new Map,Me=new Map;for(let R of re){let K=Date.now(),ve=await this.executeTool(R,d,i,$);X.set(R.id,Date.now()-K),Me.set(R.id,ve)}}}finally{W=!0,clearInterval(z)}for(;H.length>0;)yield H.shift();await new Promise(R=>setTimeout(R,0)),y(`[AIClient][${n}] stream() tool batch completed in ${Date.now()-ue}ms`);for(let R of re){let K=Me.get(R.id),ve=typeof K=="string"?K:JSON.stringify(K),Ot=ft-xe,$T=X.get(R.id)??0,oa=ve.startsWith("data:image/"),Ie;oa?Ie=ve:xe+ve.length>ft?(O(`[AIClient][${n}] Tool output budget exceeded (${ft} chars)`),Ie=this.budgetTruncate(ve,Ot)):typeof K=="string"&&K.length>this.toolResultMaxChars?Ie=`${K.slice(0,this.toolResultMaxChars)}
416
- [TRUNCATED tool result: ${K.length} chars]`:Ie=ve;let na=typeof Ie=="string"?Ie:JSON.stringify(Ie);oa||(xe+=na.length),E.push({role:"tool",tool_call_id:R.id,content:Ie}),yield{delta:"",tool_calls:[{...R,result:na,duration:$T}]}}y(`[AIClient][${n}] Round tool output size: ${xe} chars (budget: ${ft})`),Tt("debug")&&(y(`[AIClient][${n}] stream() after_tools messages=${E.length}`),xn(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 w=new Set(e.tools.map(x=>x.function.name)),k=b.filter(x=>!w.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),w=b.length>0?{...e,tools:b}:e;return{request:this.injectRequestToolGuidance(w,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 w=b-d.length;w>0&&P(`[AIClient] Mode "${t.displayName}" filtered out ${w} tools`)}let g=this.schemasToToolCallRequests(this.mergeSchemas(d,c));if(g.length===0)return{request:e,requestToolMap:o};let T={...e,tools:g};return i.toolSearch?.enabled&&m&&(T=this.injectToolSearchPrompt(T)),{request:this.injectRequestToolGuidance(T,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(p=>p.function.name));if(o.size===0)return e;let n="<!-- TOOLPACK_REQUEST_TOOL_GUIDANCE -->",s=[],i=o.has("mind_believe");if(o.has("knowledge_search")||o.has("knowledge_add")){let p=["Knowledge Base:"];if(o.has("knowledge_search")&&p.push("- Use `knowledge_search` proactively whenever the user asks about anything that could have been stored, including personal facts about the user, their preferences, names, past decisions, domain-specific information or anything that could have been stored in the memory. Search before concluding you do not know something."),o.has("knowledge_add")){let m=i?"- Use `knowledge_add` for factual domain knowledge: documents, research, technical references, or organizational information shared across agents. Do NOT use it for personal user facts or preferences \u2014 use `mind_believe` for those.":"- 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.";p.push(m)}s.push(p.join(`
413
+ </rules>`;return this.modeCache.set(n,{value:p,cachedAt:Date.now()}),p}clearCache(){this.modeCache.clear()}async collectFromFolder(e,t){let o=rw(e);try{await this.collectRecursive(o,t)}catch{}}async collectRecursive(e,t){let o=await nw(e,{withFileTypes:!0});for(let n of o){let s=Xr(e,n.name);n.isDirectory()?await this.collectRecursive(s,t):n.isFile()&&sw(n.name)===".md"&&t.add(s)}}async readFile(e,t){if(t.has(e))return t.get(e);try{let o=await ow(e,"utf-8");return t.set(e,o),o}catch{return""}}};function Sn(r,e){it("debug")&&(b(`[AIClient][${r}] Messages (${e.length}):`),e.forEach((t,o)=>{let n=t,s=typeof n.content=="string"?n.content:A(n.content,1e4);b(`[AIClient][${r}] #${o} role=${n.role} content=${s}`)}))}function Aa(r){let e=rt(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=rt(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 lw{providers;defaultProvider;toolRegistry;toolsConfig;toolRouter;bm25Engine;queryClassifier;toolOrchestrator;activeMode=null;overrideSystemPrompt;disableBaseContext;disableToolGuidance;toolResultMaxChars;hitlConfig;onToolConfirm;conversationId;contextWindowConfig;actor;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||se,this.toolRouter=new Bt,this.bm25Engine=new Ut,this.queryClassifier=new Ct,this.toolOrchestrator=new kn,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1,this.disableToolGuidance=e.disableToolGuidance||!1;let t=this.toolsConfig.resultMaxChars??se.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.actor=e.actor,this.providerModelCache=new Map,this.ruleLoader=new kt,this.contextWindowConfig&&this.contextWindowConfig.enabled!==!1&&(this.contextWindowStateManager=xa(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:ga(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=ya(s.messages,c,n),d=new Set(p.pruneInfo.removedMessages),m=s.messages.filter(y=>!d.has(y)),g={...s,messages:m};if(this.contextWindowStateManager&&this.contextWindowStateManager.recordPruneOperation(this.getConversationId(),p.tokensReclaimed),await this.countRequestTokens(g,t,g.model)<=o||m.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=Ta(a,{model:c,maxSummaryTokens:500}),d=await t.generate({model:c,messages:p,max_tokens:500,temperature:0,response_format:"text"});if(!d.content)throw new Wt("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let m=await this.countRequestTokens({...e,messages:a},t,c),g=wa(d.content,a,m),T=ba(g);if(!T.valid)throw new Wt(`Summarization result is invalid: ${T.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",d.content);let y=zr(g.summary,a.length),w=[...n,y,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),g.tokensSaved),{...e,messages:w}}async enforceContextWindow(e,t){if(!this.contextWindowConfig||this.contextWindowConfig.enabled===!1)return e;let o=await this.pruneToMaxMessageHistory(e),n=await this.getModelInfo(t,o.model),s=n?.contextWindow??1e5,i=o.max_tokens??n?.maxOutputTokens??1024,a=this.contextWindowConfig.outputTokenBuffer??1.15,c=ha(i,a),p=Math.max(0,s-c),d=Math.floor(s*((this.contextWindowConfig.pruneThreshold??85)/100)),m=Math.min(p,d),g=await this.countRequestTokens(o,t,o.model);if(this.contextWindowStateManager&&(this.contextWindowStateManager.updateTokenCount(this.getConversationId(),g),g>m&&this.contextWindowStateManager.recordWarning(this.getConversationId())),g<=m)return o;let T=this.contextWindowConfig.strategy??"prune";if(T==="fail"&&g>p)throw new qt("Context window exceeded by request messages",this.getConversationId(),g,p,T);if(T==="summarize")try{let w=await this.summarizeConversation(o,t);if(await this.countRequestTokens(w,t,w.model)<=p)return w;o=await this.pruneConversation(w,t,p)}catch{o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let y=await this.countRequestTokens(o,t,o.model);if(y>p&&T==="fail")throw new qt("Context window exceeded after attempted cleanup",this.getConversationId(),y,p,T);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 I("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new I(`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 I(`Provider '${e}' not found`,"PROVIDER_NOT_FOUND",404);this.defaultProvider=e}getToolRegistry(){return this.toolRegistry}getProviders(){return new Map(this.providers)}setToolRegistry(e){this.toolRegistry=e}setToolsConfig(e){this.toolsConfig=e}setSystemPrompt(e){this.overrideSystemPrompt=e}setMode(e){this.activeMode=e,S(`[AIClient] Mode set to: ${e?e.displayName:"none (cleared)"}`)}getMode(){return this.activeMode}getQueryClassifier(){return this.queryClassifier}reindexTools(){this.toolRegistry&&(this.bm25Engine.index(this.toolRegistry.getAll()),S(`[AIClient] Re-indexed ${this.bm25Engine.getIndexedCount()} tools for BM25 search`))}clearToolDiscoveryCache(){this.toolRouter.clearDiscoveryCache()}async generate(e,t,o){let n=this.getProvider(t);try{let s=this.newRequestId(),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=t||this.defaultProvider,d=await this.enrichRequestWithTools(c,i),m=d.request,g=d.requestToolMap;m=await this.enforceContextWindow(m,n);let T=a.toolChoicePolicy||process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||"auto",y=(m.tools?.length||0)>0,w=m.tool_choice!=null,k=Aa(m.messages),C=Ma(m.messages);!w&&y&&(T==="required"||T==="required_for_actions"&&k)&&(m.tool_choice="required");let v=n?.constructor?.name||"UnknownProvider",P=i?.response_format,E={...this.stripRequestTools(m),__toolpack_request_id:s,...P?{response_format:P}:{}};S(`[AIClient][${s}] generate() start provider=${p} class=${v} model=${m.model} messages=${m.messages.length} tools=${m.tools?.length||0} tool_choice=${m.tool_choice??"unset"} policy=${T} needsTools=${k} autoExecute=${a.enabled&&a.autoExecute}`),Qr(s,m.tools),Sn(s,m.messages);let j=te=>ua(()=>n.generate(te),{onRetry:(B,Y)=>S(`[AIClient][${s}] Rate limited \u2014 retrying in ${Y/1e3}s (attempt ${B}/3)`)}),R=await j(E);if(b(`[AIClient][${s}] generate() initial response finish_reason=${R.finish_reason??"unknown"} tool_calls=${R.tool_calls?.length||0} content=${R.content||""}`),a.autoExecute&&(this.toolRegistry||g.size>0||(i?.customTools?.length??0)>0)){let te=rt(m.messages),B=this.queryClassifier.classify(te),Y=a.maxToolRounds,we=m.maxToolRounds!==void 0?m.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(B,Y);m.maxToolRounds!==void 0?b(`[AIClient][${s}] maxToolRounds overridden per-request: ${we} (classifier bypassed)`):we!==Y?S(`[AIClient][${s}] Query classified as ${B.type} (confidence: ${B.confidence.toFixed(2)}), adjusted maxToolRounds: ${Y} \u2192 ${we}`):b(`[AIClient][${s}] Query classified as ${B.type} (confidence: ${B.confidence.toFixed(2)}), keeping maxToolRounds: ${we}`);let ae=0,J=[...m.messages];for(R.tool_calls&&R.tool_calls.length>0&&S(`[AIClient] Received ${R.tool_calls.length} tool call(s): ${R.tool_calls.map(z=>z.name).join(", ")}`);R.tool_calls&&R.tool_calls.length>0&&ae<we;){if(e.signal?.aborted){S(`[AIClient][${s}] generate() aborted by signal`);break}ae++,S(`[AIClient][${s}] generate() tool round ${ae}/${we} tool_calls=${R.tool_calls.length}`),J.push({role:"assistant",content:R.content||"",tool_calls:R.tool_calls.map(U=>({id:U.id,type:"function",function:{name:U.name,arguments:JSON.stringify(U.arguments)}}))});let z=this.toolOrchestrator.shouldUseParallelExecution(R.tool_calls),V=3,Ee=R.tool_calls,qe=R.tool_calls.filter(U=>U.name==="web.fetch");if(qe.length>V){S(`[AIClient][${s}] Limiting web.fetch calls from ${qe.length} \u2192 ${V} to prevent context overflow`);let U=qe.slice(0,V);Ee=[...R.tool_calls.filter(he=>he.name!=="web.fetch"),...U];let H=qe.slice(V);for(let he of H)J.push({role:"tool",tool_call_id:he.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let le=5e4,ge=0;if(z){S(`[AIClient][${s}] Using parallel execution for ${Ee.length} tools`);let U;try{U=await this.toolOrchestrator.executeWithDependencies(Ee,D=>this.executeTool(D,g,i,ae),5)}catch(D){ue(`[AIClient][${s}] Parallel tool execution failed: ${D.message}`),U=new Map(Ee.map(H=>[H.id,JSON.stringify({error:D.message??"Tool execution failed"})]))}for(let D of Ee){let H=U.get(D.id)??JSON.stringify({error:"Tool execution result missing"}),he=typeof H=="string"?H:JSON.stringify(H),Tt=le-ge,oe=he.startsWith("data:image/"),ne;oe?ne=he:ge+he.length>le?(M(`[AIClient][${s}] Tool output budget exceeded (${le} chars)`),ne=this.budgetTruncate(he,Tt)):typeof H=="string"&&H.length>this.toolResultMaxChars?ne=`${H.slice(0,this.toolResultMaxChars)}
414
+ [TRUNCATED tool result: ${H.length} chars]`:ne=he;let $=typeof ne=="string"?ne:JSON.stringify(ne);oe||(ge+=$.length),J.push({role:"tool",tool_call_id:D.id,content:ne})}b(`[AIClient][${s}] Round tool output size: ${ge} chars (budget: ${le})`)}else{S(`[AIClient][${s}] Using sequential execution for ${Ee.length} tools`);for(let U of Ee){let D;try{D=await this.executeTool(U,g,i,ae)}catch($){D=JSON.stringify({error:$.message??"Tool execution failed"})}let H=typeof D=="string"?D:JSON.stringify(D),he=le-ge,Tt=H.startsWith("data:image/"),oe;Tt?oe=H:ge+H.length>le?(M(`[AIClient][${s}] Tool output budget exceeded (${le} chars)`),oe=this.budgetTruncate(H,he)):typeof D=="string"&&D.length>this.toolResultMaxChars?oe=`${D.slice(0,this.toolResultMaxChars)}
415
+ [TRUNCATED tool result: ${D.length} chars]`:oe=H;let ne=typeof oe=="string"?oe:JSON.stringify(oe);Tt||(ge+=ne.length),J.push({role:"tool",tool_call_id:U.id,content:oe})}b(`[AIClient][${s}] Round tool output size: ${ge} chars (budget: ${le})`)}let Ie={...m,messages:J,__toolpack_request_id:s,...P?{response_format:P}:{}},We=o?.getLatestRequestTools?.()??[];if(We.length>0){let U=new Map((m.requestTools??[]).map(D=>[D.name,D]));for(let D of We)U.set(D.name,D);Ie.requestTools=Array.from(U.values());for(let D of We)g.set(D.name,D)}let Se=this.stripRequestTools((await this.enrichRequestWithTools(Ie,i)).request);Se=await this.enforceContextWindow(Se,n),Se.tool_choice==="required"&&(Se.tool_choice=C?"none":"auto",S(`[AIClient][${s}] generate() followup tool_choice override required->${Se.tool_choice}`)),it("debug")&&(b(`[AIClient][${s}] generate() followup request messages=${J.length}`),Sn(s,J)),R=await j(Se),b(`[AIClient][${s}] generate() followup response finish_reason=${R.finish_reason??"unknown"} tool_calls=${R.tool_calls?.length||0} content=${R.content||""}`)}if(ae>=we&&!e.signal?.aborted&&R.tool_calls&&R.tool_calls.length>0){S(`[AIClient][${s}] Tool-round cap (${we}) hit with pending tool calls; requesting graceful conclusion`),J.push({role:"assistant",content:R.content||"",tool_calls:R.tool_calls.map(V=>({id:V.id,type:"function",function:{name:V.name,arguments:JSON.stringify(V.arguments)}}))});for(let V of R.tool_calls)J.push({role:"tool",tool_call_id:V.id,content:"[Tool call skipped: maximum tool rounds reached]"});J.push({role:"user",content:"You have reached the maximum number of tool calls allowed. Do not call any more tools. Based on what you have gathered so far, either complete the task or clearly explain what you were unable to accomplish and why."});let z={...m,messages:J,__toolpack_request_id:s,tools:[],requestTools:[],tool_choice:void 0};try{R=await j(await this.enforceContextWindow(z,n)),S(`[AIClient][${s}] Graceful conclusion received content_length=${R.content?.length??0}`)}catch(V){M(`[AIClient][${s}] Graceful conclusion call failed: ${V?.message??V}; returning last response`)}}}return R.data===void 0&&R.content&&e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(R.data=e.response_format.parse(JSON.parse(R.content))),R}catch(s){throw this.wrapError(s)}}async*stream(e,t,o){let n=this.getProvider(t);try{let s=this.newRequestId(),i=t||this.defaultProvider,a=this.resolveRequestMode(e),c=a?.toolsConfig?{...this.toolsConfig,...a.toolsConfig}:this.toolsConfig,p=this.injectBaseAgentContext(e,a);p=this.injectOverrideSystemPrompt(p),p=this.injectModeSystemPrompt(p,a),p=await this.injectModeRules(p,a);let d=await this.enrichRequestWithTools(p,a),m=d.request,g=d.requestToolMap;m=await this.enforceContextWindow(m,n);let T=c.toolChoicePolicy||process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||"auto",y=(m.tools?.length||0)>0,w=m.tool_choice!=null,k=Aa(m.messages),C=Ma(m.messages);!w&&y&&(T==="required"||T==="required_for_actions"&&k)&&(m.tool_choice="required");let v=n?.constructor?.name||"UnknownProvider",P=a?.response_format,E={...this.stripRequestTools(m),__toolpack_request_id:s,...P?{response_format:P}:{}};if(S(`[AIClient][${s}] stream() start provider=${i} class=${v} model=${m.model} messages=${m.messages.length} tools=${m.tools?.length||0} tool_choice=${m.tool_choice??"unset"} policy=${T} needsTools=${k} autoExecute=${c.enabled&&c.autoExecute}`),Qr(s,m.tools),Sn(s,m.messages),!c.autoExecute||!this.toolRegistry&&g.size===0&&(a?.customTools?.length??0)===0){yield*n.stream(E);return}let j=[...m.messages],R=0,te=!1,B=rt(m.messages),Y=this.queryClassifier.classify(B),we=c.maxToolRounds,ae=m.maxToolRounds!==void 0?m.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(Y,we);for(m.maxToolRounds!==void 0?b(`[AIClient][${s}] stream() maxToolRounds overridden per-request: ${ae} (classifier bypassed)`):ae!==we&&S(`[AIClient][${s}] stream() Query classified as ${Y.type} (confidence: ${Y.confidence.toFixed(2)}), adjusted maxToolRounds: ${we} \u2192 ${ae}`);R<=ae;){if(e.signal?.aborted){S(`[AIClient][${s}] stream() aborted by signal`);return}let J="",z=[];R++,S(`[AIClient][${s}] stream() round_start ${R}/${ae}`);let V=null,Ee={...m,messages:j,...P?{response_format:P}:{}},qe=o?.getLatestRequestTools?.()??[];if(qe.length>0){let $=new Map((m.requestTools??[]).map(F=>[F.name,F]));for(let F of qe)$.set(F.name,F);Ee.requestTools=Array.from($.values());for(let F of qe)g.set(F.name,F)}let le=this.stripRequestTools((await this.enrichRequestWithTools(Ee,a)).request);le=await this.enforceContextWindow(le,n),R>1&&le.tool_choice==="required"&&(le.tool_choice=C?"none":"auto",S(`[AIClient][${s}] stream() round_${R} tool_choice override required->${le.tool_choice}`));for await(let $ of n.stream(le)){if(e.signal?.aborted){S(`[AIClient][${s}] stream() aborted by signal during chunk processing`);return}$.tool_calls&&$.tool_calls.length>0&&(z.push(...$.tool_calls),b(`[AIClient][${s}] stream() tool_calls_chunk count=${$.tool_calls.length} names=${$.tool_calls.map(F=>F.name).join(", ")}`),yield $),$.delta&&(J+=$.delta,yield $),$.finish_reason&&(V=$.finish_reason),$.finish_reason==="stop"&&(yield $)}if(b(`[AIClient][${s}] stream() round_end finish_reason=${V??"unknown"} accumulated_len=${J.length} tool_calls_total=${z.length} content=${J}`),z.length===0)break;S(`[AIClient][${s}] stream() received ${z.length} tool call(s): ${z.map($=>$.name).join(", ")}`),S(`[AIClient][${s}] stream() tool round ${R}/${ae}`),j.push({role:"assistant",content:J||"",tool_calls:z.map($=>({id:$.id,type:"function",function:{name:$.name,arguments:JSON.stringify($.arguments)}}))});let ge=3,Ie=z,We=z.filter($=>$.name==="web.fetch");if(We.length>ge){S(`[AIClient][${s}] Limiting web.fetch calls from ${We.length} \u2192 ${ge} to prevent context overflow`);let $=We.slice(0,ge);Ie=[...z.filter(Ft=>Ft.name!=="web.fetch"),...$];let _e=We.slice(ge);for(let Ft of _e)j.push({role:"tool",tool_call_id:Ft.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let Se=5e4,U=0,D=[],H=!1,he=setInterval(()=>{H||D.push({delta:""})},500),Tt=Date.now(),oe,ne;try{if(Ie.length>=2)S(`[AIClient][${s}] stream() using parallel execution for ${Ie.length} tools`),ne=new Map,oe=await this.toolOrchestrator.executeWithDependencies(Ie,async $=>{let F=Date.now(),_e=await this.executeTool($,g,a,R);return ne.set($.id,Date.now()-F),_e},5);else{S(`[AIClient][${s}] stream() executing single tool sequentially`),ne=new Map,oe=new Map;for(let $ of Ie){let F=Date.now(),_e=await this.executeTool($,g,a,R);ne.set($.id,Date.now()-F),oe.set($.id,_e)}}}finally{H=!0,clearInterval(he)}for(;D.length>0;)yield D.shift();await new Promise($=>setTimeout($,0)),b(`[AIClient][${s}] stream() tool batch completed in ${Date.now()-Tt}ms`);for(let $ of Ie){let F=oe.get($.id),_e=typeof F=="string"?F:JSON.stringify(F),Ft=Se-U,NT=ne.get($.id)??0,aa=_e.startsWith("data:image/"),Ue;aa?Ue=_e:U+_e.length>Se?(M(`[AIClient][${s}] Tool output budget exceeded (${Se} chars)`),Ue=this.budgetTruncate(_e,Ft)):typeof F=="string"&&F.length>this.toolResultMaxChars?Ue=`${F.slice(0,this.toolResultMaxChars)}
416
+ [TRUNCATED tool result: ${F.length} chars]`:Ue=_e;let la=typeof Ue=="string"?Ue:JSON.stringify(Ue);aa||(U+=la.length),j.push({role:"tool",tool_call_id:$.id,content:Ue}),yield{delta:"",tool_calls:[{...$,result:la,duration:NT}]}}b(`[AIClient][${s}] Round tool output size: ${U} chars (budget: ${Se})`),it("debug")&&(b(`[AIClient][${s}] stream() after_tools messages=${j.length}`),Sn(s,j)),R>ae&&(te=!0)}if(te&&!e.signal?.aborted){S(`[AIClient][${s}] Tool-round cap (${ae}) hit; requesting graceful conclusion`),j.push({role:"user",content:"You have reached the maximum number of tool calls allowed. Do not call any more tools. Based on what you have gathered so far, either complete the task or clearly explain what you were unable to accomplish and why."});let J={...m,messages:j,tools:[],requestTools:[],tool_choice:void 0};try{let z=await this.enforceContextWindow(J,n);for await(let V of n.stream(z)){if(e.signal?.aborted)break;yield V}S(`[AIClient][${s}] Graceful conclusion stream complete`)}catch(z){M(`[AIClient][${s}] Graceful conclusion stream failed: ${z?.message??z}`)}}}catch(s){throw this.wrapError(s)}}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 S(`[AIClient] Mode "${t.displayName}" blocks all tools`),{request:e,requestToolMap:new Map};let o=this.buildRequestToolMap(e.requestTools),n=Array.from(o.values()).map(y=>this.requestToolToSchema(y)),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 b("[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}:{}}},b(`[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){b(`[AIClient] Request already has ${e.tools.length} tools`);let x=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(c)),v=x===e.tools?e:{...e,tools:x};return{request:this.injectRequestToolGuidance(v,x),requestToolMap:o}}let y=await this.toolRouter.resolve(e.messages,this.toolRegistry,p);if(b(`[AIClient] Resolved ${y.length} tools to send: ${y.map(x=>x.name).join(", ")||"none"}`),t&&y.length>0){let x=y.length;y=this.filterSchemasByMode(y,t);let v=x-y.length;v>0&&S(`[AIClient] Mode "${t.displayName}" filtered out ${v} tools`)}let w=new Set(e.tools.map(x=>x.function.name)),k=y.filter(x=>!w.has(x.name)).map(x=>({type:"function",function:{name:x.name,description:x.description,parameters:x.parameters}}));if(k.length===0){b(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`);let x=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(c)),v=x===e.tools?e:{...e,tools:x};return{request:this.injectRequestToolGuidance(v,x),requestToolMap:o}}let C={...e,tools:this.mergeToolCallRequests([...e.tools,...k],this.schemasToToolCallRequests(c))};return p.toolSearch?.enabled&&this.toolRegistry&&(C=this.injectToolSearchPrompt(C)),{request:this.injectRequestToolGuidance(C,C.tools),requestToolMap:o}}if(!this.toolRegistry){b("[AIClient] Tool registry not configured, skipping tool resolution");let y=this.schemasToToolCallRequests(c),w=y.length>0?{...e,tools:y}:e;return{request:this.injectRequestToolGuidance(w,y),requestToolMap:o}}let d=this.toolRegistry,m=await this.toolRouter.resolve(e.messages,d,p);if(b(`[AIClient] Resolved ${m.length} tools to send: ${m.map(y=>y.name).join(", ")||"none"}`),t&&m.length>0){let y=m.length;m=this.filterSchemasByMode(m,t);let w=y-m.length;w>0&&S(`[AIClient] Mode "${t.displayName}" filtered out ${w} tools`)}let g=this.schemasToToolCallRequests(this.mergeSchemas(m,c));if(g.length===0)return{request:e,requestToolMap:o};let T={...e,tools:g};return i.toolSearch?.enabled&&d&&(T=this.injectToolSearchPrompt(T)),{request:this.injectRequestToolGuidance(T,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){if(this.disableToolGuidance)return e;let o=new Set((t||e.tools||[]).map(p=>p.function.name));if(o.size===0)return e;let n="<!-- TOOLPACK_REQUEST_TOOL_GUIDANCE -->",s=[],i=o.has("mind_believe");if(o.has("knowledge_search")||o.has("knowledge_add")){let p=["Knowledge Base:"];if(o.has("knowledge_search")&&p.push("- Use `knowledge_search` proactively whenever the user asks about anything that could have been stored, including personal facts about the user, their preferences, names, past decisions, domain-specific information or anything that could have been stored in the memory. Search before concluding you do not know something."),o.has("knowledge_add")){let d=i?"- Use `knowledge_add` for factual domain knowledge: documents, research, technical references, or organizational information shared across agents. Do NOT use it for personal user facts or preferences \u2014 use `mind_believe` for those.":"- 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.";p.push(d)}s.push(p.join(`
417
417
  `))}if(i||o.has("mind_reflect")||o.has("mind_recall")){let p=["Agent Memory (Mind):"];i&&p.push("- Use `mind_believe` to record what you have personally learned about this user: their preferences, habits, stated personal facts (names, family, job, decisions), or anything you should remember about them across future conversations. Call it at the end of your response when you learn something personal. Always prefer `mind_believe` over `knowledge_add` for personal user facts."),o.has("mind_reflect")&&p.push("- Use `mind_reflect` to record a lesson learned, standing rule, or observation from this interaction that should influence future behaviour."),o.has("mind_recall")&&p.push("- Use `mind_recall` to search your personal memory before answering questions about the user or recalling past decisions."),s.push(p.join(`
418
418
  `))}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 a=`${n}
419
419
  ${s.join(`
420
420
 
421
- `)}`,c=e.messages.findIndex(p=>p.role==="system");if(c>=0){let p=e.messages.map((m,d)=>{if(d!==c)return m;let g=typeof m.content=="string"?m.content:"";return g.includes(n)?m:{...m,content:`${g}
421
+ `)}`,c=e.messages.findIndex(p=>p.role==="system");if(c>=0){let p=e.messages.map((d,m)=>{if(m!==c)return d;let g=typeof d.content=="string"?d.content:"";return g.includes(n)?d:{...d,content:`${g}
422
422
 
423
- ${a}`.trim()}});return{...e,messages:p}}return{...e,messages:[{role:"system",content:a},...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(yt(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
+ ${a}`.trim()}});return{...e,messages:p}}return{...e,messages:[{role:"system",content:a},...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"?(M(`[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(vt(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 b(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. mode=${t?.name}, systemPrompt=${t?.systemPrompt?.substring(0,50)}`),e;let o=t.systemPrompt;if(b(`[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}
424
424
 
425
- ${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
+ ${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(b(`[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}
426
426
 
427
427
  ${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}
428
428
 
429
- ${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||xa({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
+ ${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||_a({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(d=>{if(d.role==="system"){let m=typeof d.content=="string"?d.content:"";return{...d,content:`${a}
430
430
 
431
- ${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
+ ${m}`}}return d});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(`
432
432
  `);i&&(n=`
433
433
 
434
434
  You have these tools always available:
@@ -439,7 +439,7 @@ IMPORTANT: Tool Discovery Instructions
439
439
 
440
440
  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}
441
441
 
442
- ${Gr(this.toolRegistry)}
442
+ ${Kr(this.toolRegistry)}
443
443
 
444
444
  When you need a tool:
445
445
  1. Check if it's in your current tool list
@@ -449,62 +449,62 @@ When you need a tool:
449
449
  NEVER guess or hallucinate tool names. ALWAYS use tool.search to discover tools you don't have.
450
450
  `.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}
451
451
 
452
- ${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(yt(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??{},T={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,T),w=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:w}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:b,duration:w,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 ${w}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()}),pe(`[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([Xe()],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(w=>w.tool),a),g=new Set(d.map(w=>w.name)),T=p.length;p=p.filter(w=>g.has(w.toolName));let b=T-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=`
453
- [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 Ia from"@anthropic-ai/sdk";import{zodOutputFormat as aw}from"@anthropic-ai/sdk/helpers/zod";l();ie();var Z=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}};ie();S();var Cn=class extends Z{client;constructor(e,t){super(),this.client=new Ia({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(T=>({name:this.sanitizeToolName(T.function.name),description:T.function.description,input_schema:T.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"}`),Y(t,"Anthropic",i.messages);let a=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format;a&&(i.output_config={format:aw(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 T of p.content)T.type==="text"?m.push(T.text):T.type==="tool_use"&&d.push({id:T.id,name:this.restoreToolName(T.name,e.tools),arguments:T.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"}`),Y(t,"Anthropic",n.messages);let s=await this.client.messages.create(n,e.signal?{signal:e.signal}:void 0),i="",a="",c="",p=!1;for await(let m of s)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,i=m.content_block.id,a=m.content_block.name,c=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(c+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(y(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${a}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:i,name:this.restoreToolName(a,e.tools),arguments:JSON.parse(c||"{}")}]},p=!1),m.type==="message_stop"&&(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(()=>(et(),xt));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(`
454
- `);a&&(o=a)}}else if(i.role==="tool"&&i.tool_call_id){let a=typeof i.content=="string"?i.content:JSON.stringify(i.content),c=a.match(/^data:([\w/+.-]+);base64,(.+)$/s),p=c?c[1].startsWith("image/")?[{type:"image",source:{type:"base64",media_type:c[1],data:c[2]}}]:[{type:"document",source:{type:"base64",media_type:c[1],data:c[2]}}]:a;n.push({role:"user",content:[{type:"tool_result",tool_use_id:i.tool_call_id,content:p}]})}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(`
455
- `);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}}}if(c.type==="file"){let{url:p,mimeType:m}=c.file,d=p.match(/^data:([\w/+.-]+);base64,(.+)$/s);if(d){let[,g,T]=d;return g.startsWith("image/")?{type:"image",source:{type:"base64",media_type:g,data:T}}:{type:"document",source:{type:"base64",media_type:g,data:T}}}return m.startsWith("image/")?{type:"image",source:{type:"url",url:p}}:{type:"document",source:{type:"url",url: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 Ia.APIError){let t=e.message;return e.status===401?new fe(t,e):e.status===429?new se(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 lw from"@anthropic-ai/vertex-sdk";ie();S();var kn=class extends Z{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 lw({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}`),Y(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){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content),i=s.match(/^data:([\w/+.-]+);base64,(.+)$/s),a=i?i[1].startsWith("image/")?[{type:"image",source:{type:"base64",media_type:i[1],data:i[2]}}]:[{type:"document",source:{type:"base64",media_type:i[1],data:i[2]}}]:s;o.push({role:"user",content:[{type:"tool_result",tool_use_id:n.tool_call_id,content:a}]})}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{let s;typeof n.content=="string"||n.content===null?s=n.content??"":s=(await Promise.all(n.content.map(async i=>{if(i.type==="text")return{type:"text",text:i.text};if(i.type==="image_url"){let a=i.image_url.url;if(a.startsWith("data:")){let c=a.match(/^data:(image\/\w+);base64,(.+)$/);if(c)return{type:"image",source:{type:"base64",media_type:c[1],data:c[2]}}}return{type:"image",source:{type:"url",url:a}}}if(i.type==="image_data"||i.type==="image_file"){let{normalizeImagePart:a}=await Promise.resolve().then(()=>(et(),xt)),{data:c,mimeType:p}=await a(i);return{type:"image",source:{type:"base64",media_type:p,data:c}}}if(i.type==="file"){let{url:a,mimeType:c}=i.file,p=a.match(/^data:([\w/+.-]+);base64,(.+)$/s);if(p){let[,m,d]=p;return m.startsWith("image/")?{type:"image",source:{type:"base64",media_type:m,data:d}}:{type:"document",source:{type:"base64",media_type:m,data:d}}}return c.startsWith("image/")?{type:"image",source:{type:"url",url:a}}:{type:"document",source:{type:"url",url:a}}}return null}))).filter(Boolean),o.push({role:n.role==="user"?"user":"assistant",content:s})}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 fe(t,e):e?.status===429?new se(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 cw}from"@google/genai";import{zodToJsonSchema as pw}from"zod-to-json-schema";ie();S();var Sn=class r extends Z{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 fe("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 cw({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}`),Y(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(T=>T.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}`),Y(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(pw(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){let p=this.sanitizeToolName(c.name??c.tool_call_id),m=typeof c.content=="string"?c.content:JSON.stringify(c.content),d=m.match(/^data:([\w/+.-]+);base64,(.+)$/s),g=[{functionResponse:{name:p,response:{name:p,content:d?"File data attached as sibling part.":m}}}];return d&&g.push({inlineData:{mimeType:d[1],data:d[2]}}),{role:"function",parts:g}}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=>{if(t.type==="text")return{text:t.text};if(t.type==="image_data"){let{data:o,mimeType:n}=t.image_data??{};return{inlineData:{mimeType:n??"image/jpeg",data:o??""}}}if(t.type==="image_url")return{fileData:{mimeType:"image/jpeg",fileUri:t.image_url?.url??""}};if(t.type==="file"){let o=t.file.url.match(/^data:([\w/+.-]+);base64,(.+)$/s);return o?{inlineData:{mimeType:o[1],data:o[2]}}:{fileData:{mimeType:t.file.mimeType,fileUri:t.file.url}}}return 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(`
456
- `)}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 se(t,void 0,e):e?.status===401||e?.status===403||t.includes("UNAUTHENTICATED")||t.includes("PERMISSION_DENIED")?new fe(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 mw}from"@google/generative-ai";import{zodToJsonSchema as ja}from"zod-to-json-schema";ie();S();var Pn=class extends Z{genAI;constructor(e){super(),this.genAI=new mw(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
452
+ ${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}),S(`[AIClient] Executing tool: ${e.name} with args: ${A(e.arguments,500)}`);let i=t.get(e.name),a=i?void 0:o?.customTools?.find(d=>d.name===e.name),c=i||a?void 0:this.toolRegistry?.get(e.name);if(!i&&!a&&!this.toolRegistry){let d="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:d,duration:Date.now()-s}),JSON.stringify({error:d})}if(vt(e.name)){let d=this.executeToolSearch(e.arguments,o),m=Date.now()-s;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof d=="string"?d.substring(0,200):JSON.stringify(d).substring(0,200),duration:m}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:d,duration:m,status:"success",timestamp:Date.now()}),d}let p=i||a||c;if(!p){M(`[AIClient] Tool '${e.name}' not found in registry or mode`);let d=this.findSimilarToolName(e.name),m=d?`Tool '${e.name}' not found. Did you mean '${d}'? 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:m,duration:Date.now()-s}),JSON.stringify({error:m})}try{let d=e.arguments,m=a??c;if(m?.confirmation&&this.onToolConfirm&&!this.isBypassed(m)){this.emit("tool:confirmation_requested",{tool:m,args:d,level:m.confirmation.level,reason:m.confirmation.reason});let C=await this.onToolConfirm(m,d,{roundNumber:n,conversationId:this.conversationId});if(this.emit("tool:confirmation_resolved",{tool:m,args:d,level:m.confirmation.level,reason:m.confirmation.reason,decision:C}),C.action==="deny"){let x=`[Execution denied by user${C.reason?": "+C.reason:""}]`,v=Date.now()-s;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:x,duration:v}),this.emit("tool:log",{id:e.id,name:e.name,arguments:d,result:x,duration:v,status:"success",timestamp:Date.now()}),x}C.action==="modify"&&(d=C.args)}let g=o?.toolsConfig?.additionalConfigurations?{...this.toolsConfig?.additionalConfigurations,...o.toolsConfig.additionalConfigurations}:this.toolsConfig?.additionalConfigurations??{},T={workspaceRoot:process.cwd(),actor:(typeof this.actor=="function"?this.actor():this.actor)??void 0,config:g,log:C=>S(`[Tool] ${C}`),processRegistry:this.toolRegistry?.runtimeContext?.processRegistry,githubTokenStore:this.toolRegistry?.runtimeContext?.githubTokenStore},y=await p.execute(d,T),w=Date.now()-s;this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof y=="string"?y.startsWith("data:image/")?y:y.substring(0,200):JSON.stringify(y).substring(0,200),duration:w}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:y,duration:w,status:"success",timestamp:Date.now()});let k=typeof y=="string"?y.length:JSON.stringify(y).length;return S(`[AIClient] Tool ${e.name} executed successfully in ${w}ms result_len=${k}`),it("debug")&&b(`[AIClient] Tool ${e.name} result_preview=${A(y,400)}`),typeof y=="string"?y:JSON.stringify(y)}catch(d){let m=Date.now()-s,g=d.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:g,duration:m}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:g}),duration:m,status:"error",timestamp:Date.now()}),ue(`[AIClient] Tool ${e.name} failed: ${A(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([nt()],a).length>0))return M("[AIClient] tool.search blocked by active mode"),JSON.stringify({query:o,found:0,tools:[],hint:"tool.search is not allowed in the current mode."});S(`[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(i&&p.length===0&&(S(`[AIClient] tool.search category="${i}" returned 0 results; retrying without category filter`),p=this.bm25Engine.search(o,{limit:c})),a&&p.length>0){let m=this.filterSchemasByMode(p.map(w=>w.tool),a),g=new Set(m.map(w=>w.name)),T=p.length;p=p.filter(w=>g.has(w.toolName));let y=T-p.length;y>0&&b(`[AIClient] tool.search filtered out ${y} disallowed results for mode "${a.displayName}"`)}p.length>s&&(p=p.slice(0,s));let d=p.map(m=>m.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(o,d),b(`[AIClient] tool.search found ${p.length} tools: ${d.join(", ")||"none"}`),JSON.stringify({query:o,found:p.length,tools:p.map(m=>({name:m.tool.name,displayName:m.tool.displayName,description:m.tool.description,category:m.tool.category,parameters:m.tool.parameters,relevanceScore:Math.round(m.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 I?e:new L(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}budgetTruncate(e,t){let o=`
453
+ [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 Wa from"@anthropic-ai/sdk";import{zodOutputFormat as dw}from"@anthropic-ai/sdk/helpers/zod";l();pe();var ee=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new N(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new N(`File deletion API is not supported by ${this.getDisplayName()}`)}async countTokens(e,t){return null}};pe();_();De();var Pn=class extends ee{client;constructor(e,t){super(),this.client=new Wa({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new N("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(T=>({name:this.sanitizeToolName(T.function.name),description:T.function.description,input_schema:T.function.parameters})),e.tool_choice==="required"?i.tool_choice={type:"any"}:e.tool_choice==="none"?delete i.tools:i.tool_choice={type:"auto"},b(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&b(`[Anthropic][${t}] First tool: ${A(i.tools[0],800)}`)):b(`[Anthropic][${t}] NO TOOLS in request`),b(`[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:dw(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),d=[],m=[];for(let T of p.content)T.type==="text"?d.push(T.text):T.type==="tool_use"&&m.push({id:T.id,name:this.restoreToolName(T.name,e.tools),arguments:T.input});b(`[Anthropic][${t}] Response finish_reason=${p.stop_reason} tool_calls=${m.length} content_preview=${A(d.join(""),200)}`);let g={content:d.length>0?d.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:m.length>0?m: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(d=>({name:this.sanitizeToolName(d.function.name),description:d.function.description,input_schema:d.function.parameters})),e.tool_choice==="required"?n.tool_choice={type:"any"}:e.tool_choice==="none"?delete n.tools:n.tool_choice={type:"auto"},b(`[Anthropic][${t}] Sending ${n.tools?.length||0} tools with tool_choice: ${n.tool_choice?.type||"unset"}`),n.tools&&n.tools.length>0&&b(`[Anthropic][${t}] First tool: ${A(n.tools[0],800)}`)):b(`[Anthropic][${t}] NO TOOLS in request`),b(`[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 d of s)d.type==="content_block_start"&&d.content_block?.type==="tool_use"&&(p=!0,i=d.content_block.id,a=d.content_block.name,c=""),d.type==="content_block_delta"&&(d.delta.type==="text_delta"?yield{delta:d.delta.text}:d.delta.type==="input_json_delta"&&p&&(c+=d.delta.partial_json)),d.type==="content_block_stop"&&p&&(b(`[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),d.type==="message_stop"&&(ze(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new N("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(De(),St));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(`
454
+ `);a&&(o=a)}}else if(i.role==="tool"&&i.tool_call_id){let a=typeof i.content=="string"?i.content:JSON.stringify(i.content),c=a.match(/^data:([\w/+.-]+);base64,(.+)$/s),p=c?null:at(a),d=c?c[1].startsWith("image/")?[{type:"image",source:{type:"base64",media_type:c[1],data:c[2]}}]:[{type:"document",source:{type:"base64",media_type:c[1],data:c[2]}}]:p?p.mimeType.startsWith("image/")?[{type:"image",source:{type:"url",url:p.url}}]:[{type:"document",source:{type:"url",url:p.url}}]:a;n.push({role:"user",content:[{type:"tool_result",tool_use_id:i.tool_call_id,content:d}]})}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(`
455
+ `);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 d=p.match(/^data:(image\/\w+);base64,(.+)$/);if(d)return{type:"image",source:{type:"base64",media_type:d[1],data:d[2]}}}return{type:"image",source:{type:"url",url:p}}}if(c.type==="image_data"||c.type==="image_file"){let{data:p,mimeType:d}=await s(c);return{type:"image",source:{type:"base64",media_type:d,data:p}}}if(c.type==="file"){let{url:p,mimeType:d}=c.file,m=p.match(/^data:([\w/+.-]+);base64,(.+)$/s);if(m){let[,g,T]=m;return g.startsWith("image/")?{type:"image",source:{type:"base64",media_type:g,data:T}}:{type:"document",source:{type:"base64",media_type:g,data:T}}}return d.startsWith("image/")?{type:"image",source:{type:"url",url:p}}:{type:"document",source:{type:"url",url: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 Wa.APIError){let t=e.message;return e.status===401?new ye(t,e):e.status===429?new ce(t,void 0,e):e.status&&e.status>=400&&e.status<500?new N(t,e):new L(t,"ANTHROPIC_ERROR",e.status||500,e)}return new L("Unknown Anthropic error","UNKNOWN",500,e)}};l();import uw from"@anthropic-ai/vertex-sdk";pe();_();var Rn=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 uw({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"}),b(`[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 b(`[AnthropicVertex][${t}] Response finish_reason=${i.stop_reason} tool_calls=${c.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: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(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?s.tool_choice={type:"any"}:e.tool_choice==="none"?delete s.tools:s.tool_choice={type:"auto"}),b(`[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="",d=!1;for await(let m of i)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(d=!0,a=m.content_block.id,c=m.content_block.name,p=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&d&&(p+=m.delta.partial_json)),m.type==="content_block_stop"&&d&&(yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:a,name:this.restoreToolName(c,e.tools),arguments:JSON.parse(p||"{}")}]},d=!1),m.type==="message_stop"&&(yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new N("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){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content),i=s.match(/^data:([\w/+.-]+);base64,(.+)$/s),a=i?i[1].startsWith("image/")?[{type:"image",source:{type:"base64",media_type:i[1],data:i[2]}}]:[{type:"document",source:{type:"base64",media_type:i[1],data:i[2]}}]:s;o.push({role:"user",content:[{type:"tool_result",tool_use_id:n.tool_call_id,content:a}]})}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{let s;typeof n.content=="string"||n.content===null?s=n.content??"":s=(await Promise.all(n.content.map(async i=>{if(i.type==="text")return{type:"text",text:i.text};if(i.type==="image_url"){let a=i.image_url.url;if(a.startsWith("data:")){let c=a.match(/^data:(image\/\w+);base64,(.+)$/);if(c)return{type:"image",source:{type:"base64",media_type:c[1],data:c[2]}}}return{type:"image",source:{type:"url",url:a}}}if(i.type==="image_data"||i.type==="image_file"){let{normalizeImagePart:a}=await Promise.resolve().then(()=>(De(),St)),{data:c,mimeType:p}=await a(i);return{type:"image",source:{type:"base64",media_type:p,data:c}}}if(i.type==="file"){let{url:a,mimeType:c}=i.file,p=a.match(/^data:([\w/+.-]+);base64,(.+)$/s);if(p){let[,d,m]=p;return d.startsWith("image/")?{type:"image",source:{type:"base64",media_type:d,data:m}}:{type:"document",source:{type:"base64",media_type:d,data:m}}}return c.startsWith("image/")?{type:"image",source:{type:"url",url:a}}:{type:"document",source:{type:"url",url:a}}}return null}))).filter(Boolean),o.push({role:n.role==="user"?"user":"assistant",content:s})}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 ye(t,e):e?.status===429?new ce(t,void 0,e):e?.status>=400&&e?.status<500?new N(t,e):new L(t||"Anthropic Vertex error","ANTHROPIC_VERTEX_ERROR",e?.status??500,e)}};l();import{GoogleGenAI as fw}from"@google/genai";import{zodToJsonSchema as gw}from"zod-to-json-schema";pe();_();De();var $n=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 ye("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 fw({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()}`;b(`[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;for(let g of a){let T=g.parts;if(Array.isArray(T))for(let y=0;y<T.length;y++){let w=T[y];w?.inlineData!==void 0&&!w.inlineData?.data&&T.splice(y--,1)}}let c=await this.ai.models.generateContent({model:o,contents:a,config:n}),{content:p,toolCalls:d,rawContent:m}=this.parseResponse(c,e.tools);if(d.length>0&&m){let g=d.map(T=>T.id).join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(g,m)}return b(`[VertexAI][${t}] Response finish_reason=${d.length>0?"tool_calls":"stop"} tool_calls=${d.length} content_preview=${A(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:d.length>0?"tool_calls":"stop",tool_calls:d.length>0?d:void 0,raw:c}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`vtx-str-${Date.now()}`;b(`[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;for(let m of a){let g=m.parts;if(Array.isArray(g))for(let T=0;T<g.length;T++){let y=g[T];y?.inlineData!==void 0&&!y.inlineData?.data&&g.splice(T--,1)}}let c=await this.ai.models.generateContentStream({model:o,contents:a,config:n}),p=[],d=[];for await(let m of c)for(let g of m.candidates??[])for(let T of g.content?.parts??[])if(d.push(T),T.functionCall){let y=T.functionCall;b(`[VertexAI][${t}] stream tool_call name=${y.name}`);let w=`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;p.push(w),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:w,name:this.restoreToolName(y.name,e.tools),arguments:y.args??{}}]}}else T.text&&(yield{delta:T.text});if(p.length>0&&d.length>0){let m=p.join("|"),g={role:"model",parts:d};this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(m,g)}}catch(t){throw this.handleError(t)}}async embed(e){throw new N("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(gw(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){let p=this.sanitizeToolName(c.name??c.tool_call_id),d=typeof c.content=="string"?c.content:JSON.stringify(c.content),m=d.match(/^data:([\w/+.-]+);base64,(.+)$/s),g=m?null:at(d),T=[{functionResponse:{name:p,response:{name:p,content:m||g?"File data attached as sibling part.":d}}}];return m&&T.push({inlineData:{mimeType:m[1],data:m[2]}}),g&&T.push({fileData:{mimeType:g.mimeType,fileUri:g.url}}),{role:"function",parts:T}}if(c.role==="assistant"&&c.tool_calls&&c.tool_calls.length>0){let p=c.tool_calls.map(g=>g.id).join("|"),d=this.rawContentCache.get(p);if(d)return d;let m=[];typeof c.content=="string"&&c.content&&m.push({text:c.content});for(let g of c.tool_calls)m.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:m}}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=>{if(t.type==="text")return{text:t.text};if(t.type==="image_data"){let{data:o,mimeType:n}=t.image_data??{};return o?{inlineData:{mimeType:n??"image/jpeg",data:o}}:null}if(t.type==="image_url"){let o=t.image_url?.url??"";return o?{fileData:{mimeType:"image/jpeg",fileUri:o}}:null}if(t.type==="file"){let o=t.file.url.match(/^data:([\w/+.-]+);base64,(.+)$/s);return o?o[2]?{inlineData:{mimeType:o[1],data:o[2]}}:null:t.file.url?{fileData:{mimeType:t.file.mimeType,fileUri:t.file.url}}:null}return 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(`
456
+ `)}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name??e.replace(/_/g,".")}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[o,n]of Object.entries(e))["additionalProperties","exclusiveMinimum","exclusiveMaximum","$schema","$id","definitions","$defs"].includes(o)||(t[o]=typeof n=="object"&&n!==null?Array.isArray(n)?n.map(s=>this.sanitizeSchema(s)):this.sanitizeSchema(n):n);return t}handleError(e){let t=e?.message??String(e);return e?.status===429||t.includes("RESOURCE_EXHAUSTED")?new ce(t,void 0,e):e?.status===401||e?.status===403||t.includes("UNAUTHENTICATED")||t.includes("PERMISSION_DENIED")?new ye(t,e):e?.status>=400&&e?.status<500?new N(t,e):new L(t||"Vertex AI Error","VERTEXAI_ERROR",e?.status??500,e)}};l();import{GoogleGenerativeAI as hw}from"@google/generative-ai";import{zodToJsonSchema as Ua}from"zod-to-json-schema";pe();_();var En=class r extends ee{genAI;rawContentCache=new Map;static RAW_CONTENT_CACHE_MAX=500;constructor(e){super(),this.genAI=new hw(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 N("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),d=JSON.stringify({file:{displayName:s}}),m=Buffer.concat([Buffer.from(`--${p}\r
457
457
  Content-Type: application/json\r
458
458
  \r
459
- ${m}\r
459
+ ${d}\r
460
460
  `),Buffer.from(`--${p}\r
461
461
  Content-Type: ${i}\r
462
462
  \r
463
463
  `),n,Buffer.from(`\r
464
464
  --${p}--\r
465
- `)]),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 T=await g.json();return{id:T.file?.name||T.name,url:T.file?.uri||T.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}`),Y(t,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||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(ja(e.response_format))}:{}}}).sendMessage(i)).response,m=[],d="";for(let g of p.candidates||[])for(let T of g.content?.parts||[])if(T.text&&(d+=T.text),T.functionCall){let b=T.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)}`),Y(o,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),c=await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||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(ja(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
+ `)]),g=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:m});if(!g.ok){let y=await g.text();throw new Error(`Gemini file upload failed: ${g.status} ${y}`)}let T=await g.json();return{id:T.file?.name||T.name,url:T.file?.uri||T.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)}))}],b(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&b(`[Gemini][${t}] First tool: ${A(e.tools[0],800)}`)):b(`[Gemini][${t}] NO TOOLS in request`),b(`[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(Ua(e.response_format))}:{}}}).sendMessage(i)).response,d=[],m="";for(let g of p.candidates||[])for(let T of g.content?.parts||[])if(T.text&&(m+=T.text),T.functionCall){let y=T.functionCall;d.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(y.name,e.tools),arguments:y.args||{}})}if(d.length>0){let g=p.candidates?.[0]?.content;if(g){let T=d.map(y=>y.id).join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(T,g)}}return b(`[Gemini][${t}] Response finish_reason=${d.length>0?"tool_calls":"stop"} tool_calls=${d.length} content_preview=${A(m,200)}`),{content:m||null,usage:{prompt_tokens:p.usageMetadata?.promptTokenCount||0,completion_tokens:p.usageMetadata?.candidatesTokenCount||0,total_tokens:p.usageMetadata?.totalTokenCount||0},finish_reason:d.length>0?"tool_calls":"stop",tool_calls:d.length>0?d: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(d=>({name:this.sanitizeToolName(d.function.name),description:d.function.description,parameters:this.sanitizeSchema(d.function.parameters)}))}]);let o=e.__toolpack_request_id||`str-${Date.now()}`;b(`[Gemini][${o}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&b(`[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),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(Ua(e.response_format))}:{}}}).sendMessageStream(i),p=[];for await(let d of c.stream){for(let m of d.candidates?.[0]?.content?.parts||[])if(m.functionCall){b(`[Gemini][${o}] Stream finish_reason=tool_calls name=${m.functionCall.name}`);let g=`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`;p.push(g),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:g,name:this.restoreToolName(m.functionCall.name,e.tools),arguments:m.functionCall.args||{}}]}}else m.text&&(yield{delta:m.text});try{let m=d.text();m&&!d.candidates?.[0]?.content?.parts?.some(g=>g.text)&&(yield{delta:m})}catch{}}if(p.length>0)try{let m=(await c.response).candidates?.[0]?.content;if(m){let g=p.join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(g,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(`
466
466
  `)).join(`
467
- `)}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(()=>(et(),xt)),a=async d=>typeof d=="string"?[{text:d}]:d===null?[]:(await Promise.all(d.map(async T=>{if(T.type==="text")return{text:T.text};if(T.type==="image_data"||T.type==="image_file"||T.type==="image_url")try{let{data:b,mimeType:w}=await i(T);return{inlineData:{mimeType:w,data:b}}}catch{return T.type==="image_url"?{text:`[Image: ${T.image_url.url}]`}:{text:"[Unresolvable Image]"}}if(T.type==="file"){let b=T.file.url.match(/^data:([\w/+.-]+);base64,(.+)$/s);return b?{inlineData:{mimeType:b[1],data:b[2]}}:{fileData:{fileUri:T.file.url,mimeType:T.file.mimeType}}}return null}))).filter(Boolean),c=await Promise.all(s.map(async d=>{if(d.role==="tool"&&d.tool_call_id){let g=this.sanitizeToolName(d.name||d.tool_call_id),T=typeof d.content=="string"?d.content:JSON.stringify(d.content),b=T.match(/^data:([\w/+.-]+);base64,(.+)$/s),w=[{functionResponse:{name:g,response:{name:g,content:b?"File data attached as sibling part.":T}}}];return b&&w.push({inlineData:{mimeType:b[1],data:b[2]}}),{role:"function",parts:w}}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 T=d.content.filter(b=>typeof b=="object"&&b.type==="text").map(b=>b.text).join(`
468
- `);T&&g.push({text:T})}for(let T of d.tool_calls)g.push({functionCall:{name:this.sanitizeToolName(T.function.name),args:typeof T.function.arguments=="string"?JSON.parse(T.function.arguments||"{}"):T.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 se(e.message,void 0,e):e.status>=400&&e.status<500?new M(e.message,e):e.message&&e.message.includes("API key")?new fe(e.message,e):new I(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();ie();import*as qe from"fs";import*as Kr from"path";var La="toolpack.config.json",_n=new Map;async function Fa(r){for(;_n.has(r);)await _n.get(r);let e,t=new Promise(o=>{e=o});return _n.set(r,t),()=>{_n.delete(r),e()}}function tt(r){if(r&&qe.existsSync(r))return r;let e=Kr.join(process.cwd(),La);return qe.existsSync(e)?e:null}function Wt(r){if(!r)return null;try{let e=qe.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function Jr(r){let e=r||tt();return Wt(e)||{}}function dw(){}function uw(r){return(Jr(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function Rn(r){return Jr(r).ollama?.baseUrl||"http://localhost:11434"}async function fw(r){let{type:e,value:t,configPath:o}=r,n=o||tt();n||(n=Kr.join(process.cwd(),La));let s=await Fa(n);try{let i=Wt(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 gw(r){let{type:e,value:t,configPath:o}=r,n=o||tt();if(!n)return;let s=await Fa(n);try{let i=Wt(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 Wa}from"zod-to-json-schema";ie();S();l();import qa from"http";function _e(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=qa.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 Vr(r,e,t,o=12e4,n){let s,i=!1;return n&&n.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let c=new URL(e,r),p={hostname:c.hostname,port:c.port,path:c.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},m=await new Promise((g,T)=>{s=qa.request(p,g),s.on("error",T),s.on("timeout",()=>{s.destroy(),T(new Error("Stream request timed out"))}),s.write(JSON.stringify(t)),s.end()});if(m.statusCode&&m.statusCode>=400){let g="";for await(let T of m)g+=T.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${g}`)}let d="";for await(let g of m){if(i)break;let T=g.toString();if(d+=T,d.includes('"error"'))try{let w=JSON.parse(d.trim());if(w.error)throw new Error(`Ollama: ${w.error}`)}catch(w){if(w.message.startsWith("Ollama:"))throw w}let b=d.split(`
469
- `);d=b.pop()||"";for(let w of b)w.trim()&&(yield w)}d.trim()&&!i&&(yield d.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var ot=class extends Z{config;baseUrl;timeout;modelName;constructor(e){super(),this.config=e,this.baseUrl=e.baseUrl||"http://localhost:11434",this.timeout=e.timeout||12e4,this.modelName=e.model}getDisplayName(){return"Ollama"}async getModels(){try{return(await this.listModels()).map(t=>({id:t.name,displayName:t.name,capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!0,vision:!0}}))}catch{return[]}}async connect(){let e=await this.listModels(),t=this.config.model.split(":")[0].toLowerCase();if(!e.some(n=>n.name.split(":")[0].toLowerCase()===t||n.name.toLowerCase()===this.config.model.toLowerCase()))throw new M(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
470
- Available models: ${e.map(n=>n.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await _e(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 Ve(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await _e(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=Wa(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}`),Y(t,"Ollama",e.messages);try{let i=await _e(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 Ve(`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=Wa(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}`),Y(t,"Ollama",e.messages);let{stream:i}=Vr(this.baseUrl,"/api/chat",s,this.timeout,e.signal);try{for await(let a of i)try{let c=JSON.parse(a);if(c.message?.content){let p=c.message.tool_calls&&c.message.tool_calls.length>0;yield{delta:c.message.content,finish_reason:c.done&&!p?"stop":void 0,usage:c.done&&c.prompt_eval_count!=null?{prompt_tokens:c.prompt_eval_count||0,completion_tokens:c.eval_count||0,total_tokens:(c.prompt_eval_count||0)+(c.eval_count||0)}:void 0}}if(c.message?.tool_calls&&c.message.tool_calls.length>0){let p=c.message.tool_calls.map(m=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}}));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 Ve(`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 _e(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 Ve(`Embedding failed for Ollama model "${n}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(et(),xt));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+`
467
+ `)}async formatHistory(e,t={}){let o=e.filter(m=>m.role!=="system");if(o.length===0)return{history:[],lastUserMessage:""};let n=o[o.length-1],s=o.slice(0,o.length-1),{normalizeImagePart:i}=await Promise.resolve().then(()=>(De(),St)),a=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async T=>{if(T.type==="text")return{text:T.text};if(T.type==="image_data"||T.type==="image_file"||T.type==="image_url")try{let{data:y,mimeType:w}=await i(T);return{inlineData:{mimeType:w,data:y}}}catch{return T.type==="image_url"?{text:`[Image: ${T.image_url.url}]`}:{text:"[Unresolvable Image]"}}if(T.type==="file"){let y=T.file.url.match(/^data:([\w/+.-]+);base64,(.+)$/s);return y?{inlineData:{mimeType:y[1],data:y[2]}}:{fileData:{fileUri:T.file.url,mimeType:T.file.mimeType}}}return null}))).filter(Boolean),c=await Promise.all(s.map(async m=>{if(m.role==="tool"&&m.tool_call_id){let g=this.sanitizeToolName(m.name||m.tool_call_id),T=typeof m.content=="string"?m.content:JSON.stringify(m.content),y=T.match(/^data:([\w/+.-]+);base64,(.+)$/s),w=[{functionResponse:{name:g,response:{name:g,content:y?"File data attached as sibling part.":T}}}];return y&&w.push({inlineData:{mimeType:y[1],data:y[2]}}),{role:"function",parts:w}}if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let g=m.tool_calls.map(w=>w.id).join("|"),T=this.rawContentCache.get(g);if(T)return T;let y=[];if(typeof m.content=="string"&&m.content)y.push({text:m.content});else if(Array.isArray(m.content)){let w=m.content.filter(k=>typeof k=="object"&&k.type==="text").map(k=>k.text).join(`
468
+ `);w&&y.push({text:w})}for(let w of m.tool_calls)y.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:y}}return{role:m.role==="user"?"user":"model",parts:await a(m.content)}})),p=[];for(let m of c){let g=p[p.length-1];m.role==="function"&&g?.role==="function"?g.parts.push(...m.parts):p.push(m)}let d=typeof n.content=="string"?n.content:await a(n.content);return{history:p,lastUserMessage:d}}handleError(e){return e.status===429?new ce(e.message,void 0,e):e.status>=400&&e.status<500?new N(e.message,e):e.message&&e.message.includes("API key")?new ye(e.message,e):new L(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();pe();import*as He from"fs";import*as Yr from"path";var Ga="toolpack.config.json",Dn=new Map;async function Ba(r){for(;Dn.has(r);)await Dn.get(r);let e,t=new Promise(o=>{e=o});return Dn.set(r,t),()=>{Dn.delete(r),e()}}function lt(r){if(r&&He.existsSync(r))return r;let e=Yr.join(process.cwd(),Ga);return He.existsSync(e)?e:null}function zt(r){if(!r)return null;try{let e=He.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function Zr(r){let e=r||lt();return zt(e)||{}}function yw(){}function bw(r){return(Zr(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function An(r){return Zr(r).ollama?.baseUrl||"http://localhost:11434"}async function Tw(r){let{type:e,value:t,configPath:o}=r,n=o||lt();n||(n=Yr.join(process.cwd(),Ga));let s=await Ba(n);try{let i=zt(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{He.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new I(`Failed to write bypass rule to config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}}finally{s()}}async function ww(r){let{type:e,value:t,configPath:o}=r,n=o||lt();if(!n)return;let s=await Ba(n);try{let i=zt(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{He.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new I(`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 Ha}from"zod-to-json-schema";pe();_();l();import za from"http";function Ae(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=za.request(c,d=>{let m=[];d.on("data",g=>m.push(g)),d.on("end",()=>{s({status:d.statusCode||0,body:Buffer.concat(m).toString("utf-8")})})});p.on("error",d=>i(d)),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},d=await new Promise((g,T)=>{s=za.request(p,g),s.on("error",T),s.on("timeout",()=>{s.destroy(),T(new Error("Stream request timed out"))}),s.write(JSON.stringify(t)),s.end()});if(d.statusCode&&d.statusCode>=400){let g="";for await(let T of d)g+=T.toString();throw new Error(`Ollama HTTP ${d.statusCode}: ${g}`)}let m="";for await(let g of d){if(i)break;let T=g.toString();if(m+=T,m.includes('"error"'))try{let w=JSON.parse(m.trim());if(w.error)throw new Error(`Ollama: ${w.error}`)}catch(w){if(w.message.startsWith("Ollama:"))throw w}let y=m.split(`
469
+ `);m=y.pop()||"";for(let w of y)w.trim()&&(yield w)}m.trim()&&!i&&(yield m.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var ct=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 N(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
470
+ Available models: ${e.map(n=>n.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await Ae(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new L(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof L?e:new tt(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await Ae(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=Ha(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}})),b(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&b(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),b(`[Ollama][${t}] NO TOOLS in request`)),b(`[Ollama][${t}] generate() request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),Z(t,"Ollama",e.messages);try{let i=await Ae(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 d of a.message.tool_calls)c.push({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(d.function.name,e.tools),arguments:d.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 b(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${A(p.content,200)}`),p}catch(i){throw i instanceof L?i:new tt(`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=Ha(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}})),b(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&b(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),b(`[Ollama][${t}] NO TOOLS in request`)),b(`[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(d=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(d.function.name,e.tools),arguments:d.function.arguments||{}}));b(`[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){ze(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new tt(`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;b(`[Ollama][${t}] Embedding request: model=${n}, inputs=${o.length}`);try{let s=await Ae(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 L?s:new tt(`Embedding failed for Ollama model "${n}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(De(),St));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+`
471
471
  `;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}]
472
472
  `:o+=`[Unresolvable Image]
473
- `}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 Ut=class extends Z{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await _e(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 _e(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 _e(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 Qr=[{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 hw(){return Qr[0].model}function yw(r){let e=r.toLowerCase();return Qr.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function bw(){return[...Qr]}l();import Ua from"openai";import{zodResponseFormat as Ga}from"openai/helpers/zod";ie();S();var vt=class extends Z{client;constructor(e,t){super(),this.client=new Ua({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?Ga(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)}`),Y(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?Ga(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"}`),Y(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0),a=new Map;for await(let c of i){let p=c.choices[0];if(p.finish_reason&&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){let s=typeof e.content=="string"?e.content:JSON.stringify(e.content??""),i=s.match(/^data:([\w/+.-]+);base64,(.+)$/s);return{role:"tool",tool_call_id:e.tool_call_id,content:i?i[1].startsWith("image/")?[{type:"image_url",image_url:{url:s}}]:"[File content not available inline for this provider]":s}}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(()=>(et(),xt)),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}`}}}if(s.type==="file"){let{url:i,mimeType:a}=s.file;return i.startsWith("data:")?a.startsWith("image/")?{type:"image_url",image_url:{url:i}}:null:a.startsWith("image/")?{type:"image_url",image_url:{url:i}}:{type:"file",file:{url:i}}}return null}));return{role:e.role,content:n.filter(Boolean)}}handleError(e){if(e instanceof Ua.APIError){let t=e.message;return e.status===401?new fe(t,e):e.status===429?new se(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 Ba="https://openrouter.ai/api/v1",$n=class extends vt{name="openrouter";_apiKey;constructor(e,t={}){super(e,Ba),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(`${Ba}/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"}};et();l();l();var gn=class{tools=new Map;projects=new Map;config=oe;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(()=>(Qa(),Va));this.runtimeContext=new e;let{fsToolsProject:t}=await Promise.resolve().then(()=>(ys(),pp)),{execToolsProject:o}=await Promise.resolve().then(()=>(Ps(),im)),{systemToolsProject:n}=await Promise.resolve().then(()=>(As(),Wm)),{httpToolsProject:s}=await Promise.resolve().then(()=>(Fs(),kd)),{githubToolsProject:i}=await Promise.resolve().then(()=>(Qs(),Pu)),{webToolsProject:a}=await Promise.resolve().then(()=>(li(),Kf)),{codingToolsProject:c}=await Promise.resolve().then(()=>(Pi(),Ih)),{gitToolsProject:p,createGitCloneTool:m}=await Promise.resolve().then(()=>(Ri(),gy)),{diffToolsProject:d}=await Promise.resolve().then(()=>($i(),Ey)),{dbToolsProject:g}=await Promise.resolve().then(()=>(Di(),nb)),{cloudToolsProject:T}=await Promise.resolve().then(()=>(Mi(),fb)),{slackToolsProject:b}=await Promise.resolve().then(()=>(Fi(),Yb)),{k8sToolsProject:w}=await Promise.resolve().then(()=>(qi(),oT)),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,T,b,w])}};l();import*as Ke from"fs";import*as Pr from"path";S();var nT="toolpack.config.json";function rT(r){let e=sT(r);if(!Ke.existsSync(e))return{};try{let t=Ke.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function CC(r){let e=rT(r),t=SC(e.tools||e);return y(JSON.stringify(t??{})),t}function kC(r,e){let t=sT(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 SC(r){let e=r.additionalConfigurations||{};return e.webSearch||(e.webSearch={}),!e.webSearch.tavilyApiKey&&process.env.TOOLPACK_TAVILY_API_KEY&&(e.webSearch.tavilyApiKey=process.env.TOOLPACK_TAVILY_API_KEY),!e.webSearch.braveApiKey&&process.env.TOOLPACK_BRAVE_API_KEY&&(e.webSearch.braveApiKey=process.env.TOOLPACK_BRAVE_API_KEY),{enabled:r.enabled??oe.enabled,autoExecute:r.autoExecute??oe.autoExecute,maxToolRounds:r.maxToolRounds??oe.maxToolRounds,toolChoicePolicy:r.toolChoicePolicy??oe.toolChoicePolicy,resultMaxChars:r.resultMaxChars??oe.resultMaxChars,enabledTools:r.enabledTools??oe.enabledTools,enabledToolCategories:r.enabledToolCategories??oe.enabledToolCategories,toolSearch:r.toolSearch??oe.toolSearch,additionalConfigurations:e}}function sT(r){return r?r.endsWith(".json")?Pr.resolve(r):Pr.resolve(r,nT):Pr.resolve(process.cwd(),nT)}l();S();function PC(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}}Ft();ys();Ps();As();Fs();Qs();li();Pi();Ri();$i();Di();Mi();qi();Fi();l();l();S();import{spawn as _C}from"child_process";import{EventEmitter as RC}from"events";var _r=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},hn=class extends RC{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=_C(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=>{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 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(`
474
- `))!==-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((c,p)=>{let m;i>0&&(m=setTimeout(()=>{let d=this.messageQueue.get(s);d&&(this.messageQueue.delete(s),d.reject(new _r(t,i)))},i)),this.messageQueue.set(s,{resolve:c,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
475
- `)}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 Rr=class{constructor(e){this.config=e}config;clients=new Map;serverConfigs=new Map;toolDefinitions=new Map;toolOwners=new Map;async connectServer(e){let{name:t,displayName:o,toolPrefix:n,...s}=e;P(`[MCP] Connecting to server: ${o||t}`);try{let i=new hn({...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){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 pe(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{pe(`[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=>{pe(`[MCP] ${t} tool refresh failed after reconnect: ${n}`)})}),e.on("reconnect_failed",o=>{pe(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{P(`[MCP] ${t} notification: ${JSON.stringify(o)}`)})}removeServerToolDefinitions(e){for(let[t,o]of this.toolOwners)o===e&&(this.toolDefinitions.delete(t),this.toolOwners.delete(t))}async discoverServerTools(e,t,o){let s=(await t.request("tools/list"))?.tools||[];P(`[MCP] Discovered ${s.length} tools from ${e}`),this.removeServerToolDefinitions(e);let i=o.toolPrefix||`mcp.${e}.`;for(let a of s){let c=this.convertMcpTool(a,e,i,t);this.toolDefinitions.set(c.name,c),this.toolOwners.set(c.name,e)}}async refreshServerTools(e){let t=this.clients.get(e),o=this.serverConfigs.get(e);!t||!o||await this.discoverServerTools(e,t,o)}};async function Wi(r){let e=new Rr(r);await e.connectAll();let t=e.getToolDefinitions();return{manifest:{key:"mcp-tools",name:"mcp-tools",displayName:"MCP Tools",version:"1.0.0",description:`Tools from ${e.getConnectedServers().length} MCP server(s)`,category:"mcp",author:"Toolpack SDK",tools:t.map(n=>n.name)},tools:t,mcpManager:e}}async function Ui(r){"mcpManager"in r&&await r.mcpManager.disconnectAll()}l();import*as V from"fs/promises";import*as ae from"path";function Bi(r){let e={},t=r.match(/^---\n([\s\S]*?)\n---/);if(!t||!t[1])return e;for(let o of t[1].split(`
476
- `)){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 zi(r){let e=r.match(/\[(.*)\]/);return!e||!e[1]?[]:e[1].split(",").map(t=>t.trim().replace(/"/g,"")).filter(Boolean)}function Gi(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(`
477
- `).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 iT(r,e){async function t(o){let n;try{n=await V.readdir(o)}catch{return null}for(let s of n){let i=ae.join(o,s),a;try{a=await V.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 $C(r){let e=[];async function t(o){let n;try{n=await V.readdir(o)}catch{return}for(let s of n){let i=ae.join(o,s),a;try{a=await V.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function EC(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(`
478
- `),"","## Instructions","",s,""];return i&&m.push("## Examples","",i,""),m.join(`
479
- `)}function DC(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?ae.join(r,p):r;await V.mkdir(m,{recursive:!0});let d=ae.join(m,`${t}.skill.md`);try{return await V.access(d),JSON.stringify({error:"skill_exists",message:`Skill "${t}" already exists at ${d}. Use skill.update to modify it.`},null,2)}catch{}let g=EC({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:c});return await V.writeFile(d,g,"utf-8"),JSON.stringify({success:!0,skill:t,path:d,message:`Skill "${o}" created successfully`},null,2)}}}function MC(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 iT(r,t);if(!n)return JSON.stringify({error:"skill_not_found",message:`Skill "${t}" not found. Use skill.list to see available skills.`},null,2);let s=(await V.readFile(n,"utf-8")).replace(/\r\n/g,`
480
- `),i=Bi(s),a={name:i.name||t,title:i.title||t,version:i.version,tags:i.tags?zi(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:Gi(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:Gi(s),instructions:pt(s,"Instructions"),examples:pt(s,"Examples")||void 0},null,2)}}}function AC(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 iT(r,t);if(!p)return JSON.stringify({error:"skill_not_found",message:`Skill "${t}" not found. Use skill.create to create it first.`},null,2);let m=(await V.readFile(p,"utf-8")).replace(/\r\n/g,`
481
- `),d=Bi(m),g=d.tags?zi(d.tags):[],T=d.title||t,b=d.version||"1.0.0",w=o??T,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
473
+ `}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 N(`Model not found: ${o}`):new L(o,"OLLAMA_ERROR",e)}};l();var Ht=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 Ae(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 ct({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 Ae(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(a.status===200){let p=(JSON.parse(a.body).details?.families||[]).map(d=>d.toLowerCase());o=p.some(d=>["clip","mllama"].includes(d)),n=p.some(d=>d.includes("bert")||d.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 Ae(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 xw(){return ts[0].model}function vw(r){let e=r.toLowerCase();return ts.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function Cw(){return[...ts]}l();import Ka from"openai";import{zodResponseFormat as Ja}from"openai/helpers/zod";pe();_();De();var _t=class extends ee{client;constructor(e,t){super(),this.client=new Ka({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 N("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(m=>this.toOpenAIMessage(m,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?Ja(e.response_format,"structured_output"):void 0,stream:!1},s=new Map;e.tools&&e.tools.length>0&&(n.tools=e.tools.map(m=>{let g=this.sanitizeToolName(m.function.name);return s.set(g,m.function.name),{type:"function",function:{name:g,description:m.function.description,parameters:m.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",b(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),b(`[OpenAI][${t}] First tool: ${A(n.tools[0],800)}`)),b(`[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);ze(`[OpenAI][${t}] Raw completion: ${JSON.stringify(i)}`);let a=i.choices[0].message;b(`[OpenAI][${t}] Response: finish_reason=${i.choices[0].finish_reason}`),b(`[OpenAI][${t}] Response has tool_calls: ${!!a.tool_calls}, count: ${a.tool_calls?.length||0}`),b(`[OpenAI][${t}] Response content: ${JSON.stringify(a.content)}`),a.content&&b(`[OpenAI][${t}] Response content preview: ${A(a.content,200)}`);let c=i.choices[0],p,d=c.message.tool_calls;return d&&d.length>0&&(p=d.map(m=>({id:m.id,name:s.get(m.function.name)||m.function.name,arguments:JSON.parse(m.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?Ja(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",b(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),b(`[OpenAI][${t}] First tool: ${A(n.tools[0],800)}`)):b(`[OpenAI][${t}] NO TOOLS in request`),b(`[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&&ze(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let d of p.delta.tool_calls){let m=d.index;a.has(m)||a.set(m,{id:d.id||"",name:d.function?.name||"",args:""});let g=a.get(m);d.id&&(g.id=d.id),d.function?.name&&(g.name=d.function.name),d.function?.arguments&&(g.args+=d.function.arguments),ze(`[OpenAI][${t}] tool_call_delta idx=${m} id=${d.id||g.id||""} name=${d.function?.name||g.name||""} args_delta=${A(d.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 d=Array.from(a.values()).map(m=>({id:m.id,name:s.get(m.name)||m.name,arguments:JSON.parse(m.args||"{}")}));b(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${d.length} names=${d.map(m=>m.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:d}}}}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){let s=typeof e.content=="string"?e.content:JSON.stringify(e.content??""),i=s.match(/^data:([\w/+.-]+);base64,(.+)$/s),a=i?null:at(s);return{role:"tool",tool_call_id:e.tool_call_id,content:i?i[1].startsWith("image/")?[{type:"image_url",image_url:{url:s}}]:"[File content not available inline for this provider]":a?a.mimeType.startsWith("image/")?[{type:"image_url",image_url:{url:a.url}}]:"[File content not available inline for this provider]":s}}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(()=>(De(),St)),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}`}}}if(s.type==="file"){let{url:i,mimeType:a}=s.file;return i.startsWith("data:")?a.startsWith("image/")?{type:"image_url",image_url:{url:i}}:null:a.startsWith("image/")?{type:"image_url",image_url:{url:i}}:{type:"file",file:{url:i}}}return null}));return{role:e.role,content:n.filter(Boolean)}}handleError(e){if(e instanceof Ka.APIError){let t=e.message;return e.status===401?new ye(t,e):e.status===429?new ce(t,void 0,e):e.status&&e.status>=400&&e.status<500?new N(t,e):new L(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new L("Unknown error","UNKNOWN",500,e)}};l();var Va="https://openrouter.ai/api/v1",Mn=class extends _t{name="openrouter";_apiKey;constructor(e,t={}){super(e,Va),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(`${Va}/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"}};De();l();l();var Tn=class{tools=new Map;projects=new Map;config=se;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(()=>(tl(),el));this.runtimeContext=new e;let{fsToolsProject:t}=await Promise.resolve().then(()=>(vs(),gp)),{execToolsProject:o}=await Promise.resolve().then(()=>(Ds(),mm)),{systemToolsProject:n}=await Promise.resolve().then(()=>(Ls(),Hm)),{httpToolsProject:s}=await Promise.resolve().then(()=>(Bs(),$d)),{githubToolsProject:i}=await Promise.resolve().then(()=>(ti(),Du)),{webToolsProject:a}=await Promise.resolve().then(()=>(ui(),Yf)),{codingToolsProject:c}=await Promise.resolve().then(()=>(Di(),Wh)),{gitToolsProject:p,createGitCloneTool:d}=await Promise.resolve().then(()=>(Mi(),wy)),{diffToolsProject:m}=await Promise.resolve().then(()=>(Ni(),Oy)),{dbToolsProject:g}=await Promise.resolve().then(()=>(Ii(),lb)),{cloudToolsProject:T}=await Promise.resolve().then(()=>(ji(),Tb)),{slackToolsProject:y}=await Promise.resolve().then(()=>(Bi(),nT)),{k8sToolsProject:w}=await Promise.resolve().then(()=>(zi(),aT)),k={...p,tools:p.tools.map(C=>C.name==="git.clone"?d(this.runtimeContext.cloneState):C)};await this.loadProjects([t,o,n,s,i,a,c,k,m,g,T,y,w])}};l();import*as Ze from"fs";import*as Er from"path";_();var lT="toolpack.config.json";function cT(r){let e=pT(r);if(!Ze.existsSync(e))return{};try{let t=Ze.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function RC(r){let e=cT(r),t=EC(e.tools||e);return b(JSON.stringify(t??{})),t}function $C(r,e){let t=pT(e),o={};try{Ze.existsSync(t)&&(o=JSON.parse(Ze.readFileSync(t,"utf-8")))}catch{o={}}o.tools=r,Ze.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function EC(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??se.enabled,autoExecute:r.autoExecute??se.autoExecute,maxToolRounds:r.maxToolRounds??se.maxToolRounds,toolChoicePolicy:r.toolChoicePolicy??se.toolChoicePolicy,resultMaxChars:r.resultMaxChars??se.resultMaxChars,enabledTools:r.enabledTools??se.enabledTools,enabledToolCategories:r.enabledToolCategories??se.enabledToolCategories,toolSearch:r.toolSearch??se.toolSearch,additionalConfigurations:e}}function pT(r){return r?r.endsWith(".json")?Er.resolve(r):Er.resolve(r,lT):Er.resolve(process.cwd(),lT)}l();_();function DC(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&&M(`[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();vs();Ds();Ls();Bs();ti();ui();Di();Mi();Ni();Ii();ji();zi();Bi();l();l();_();import{spawn as AC}from"child_process";import{EventEmitter as MC}from"events";var Dr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},Le=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},wn=class extends MC{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 Le("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 Le("Failed to spawn MCP server: stdout/stdin unavailable");this.process.stdout.on("data",t=>{this.handleData(t)}),this.process.stderr&&this.process.stderr.on("data",t=>{M(`[MCP server stderr] ${t.toString().trim()}`)}),this.process.on("error",t=>{this._connected=!1,this.emit("error",t)}),this.process.on("exit",t=>{let o=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new Le(`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(`
474
+ `))!==-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 Le("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 d;i>0&&(d=setTimeout(()=>{let m=this.messageQueue.get(s);m&&(this.messageQueue.delete(s),m.reject(new Dr(t,i)))},i)),this.messageQueue.set(s,{resolve:c,reject:p,timer:d});try{this.process.stdin.write(JSON.stringify(a)+`
475
+ `)}catch(m){d&&clearTimeout(d),this.messageQueue.delete(s),p(m)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new Le("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 Le("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()}};_();var Ar=class{constructor(e){this.config=e}config;clients=new Map;serverConfigs=new Map;toolDefinitions=new Map;toolOwners=new Map;async connectServer(e){let{name:t,displayName:o,toolPrefix:n,...s}=e;S(`[MCP] Connecting to server: ${o||t}`);try{let i=new 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 ue(`[MCP] Failed to connect to ${t}: ${i}`),i}}async connectAll(){let e=this.config.servers.filter(t=>t.autoConnect!==!1).map(t=>this.connectServer(t));await Promise.allSettled(e)}async disconnectServer(e){let t=this.clients.get(e);if(!t){M(`[MCP] Server ${e} not found`);return}S(`[MCP] Disconnecting from ${e}`);for(let[o,n]of this.toolOwners)n===e&&(this.toolDefinitions.delete(o),this.toolOwners.delete(o));await t.disconnect(),this.clients.delete(e),this.serverConfigs.delete(e)}async disconnectAll(){let e=Array.from(this.clients.keys()).map(t=>this.disconnectServer(t));await Promise.allSettled(e)}getToolDefinitions(){return Array.from(this.toolDefinitions.values())}getConnectedServers(){return Array.from(this.clients.keys())}isServerConnected(e){return this.clients.get(e)?.connected??!1}convertMcpTool(e,t,o,n){let s={type:"object",properties:e.inputSchema.properties||{},required:e.inputSchema.required||[]};return{name:`${o}${e.name}`,displayName:e.name,description:e.description||`MCP tool from ${t}`,category:"mcp",parameters:s,execute:async i=>{try{S(`[MCP] Executing ${e.name} on ${t}`);let a=await n.callTool(e.name,i);return JSON.stringify(a)}catch(a){throw ue(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{ue(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{M(`[MCP] ${t} closed with code ${o}`)}),e.on("reconnecting",({attempt:o,max:n})=>{S(`[MCP] ${t} reconnecting (${o}/${n})`)}),e.on("reconnected",({attempt:o})=>{S(`[MCP] ${t} reconnected after ${o} attempts`),this.refreshServerTools(t).catch(n=>{ue(`[MCP] ${t} tool refresh failed after reconnect: ${n}`)})}),e.on("reconnect_failed",o=>{ue(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{S(`[MCP] ${t} notification: ${JSON.stringify(o)}`)})}removeServerToolDefinitions(e){for(let[t,o]of this.toolOwners)o===e&&(this.toolDefinitions.delete(t),this.toolOwners.delete(t))}async discoverServerTools(e,t,o){let s=(await t.request("tools/list"))?.tools||[];S(`[MCP] Discovered ${s.length} tools from ${e}`),this.removeServerToolDefinitions(e);let i=o.toolPrefix||`mcp.${e}.`;for(let a of s){let 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 Ar(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 X from"fs/promises";import*as me 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(`
476
+ `)){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(`
477
+ `).filter(n=>n.startsWith("- "))){let n=o.match(/^- "(.*)"/);n&&n[1]&&e.push(n[1])}return e}function yt(r,e){let t=r.match(new RegExp(`## ${e}\\n\\n([\\s\\S]*?)(?=\\n## |$)`));return t&&t[1]?t[1].trim():""}async function mT(r,e){async function t(o){let n;try{n=await X.readdir(o)}catch{return null}for(let s of n){let i=me.join(o,s),a;try{a=await X.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 NC(r){let e=[];async function t(o){let n;try{n=await X.readdir(o)}catch{return}for(let s of n){let i=me.join(o,s),a;try{a=await X.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function OC(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(m=>`"${m}"`).join(", "):"",d=["---",`name: ${e}`,`title: ${t}`,"version: 1.0.0",`updated: ${c}`,`tags: [${p}]`,"---","","## Description","",o,"","## Triggers","",n.map(m=>`- "${m}"`).join(`
478
+ `),"","## Instructions","",s,""];return i&&d.push("## Examples","",i,""),d.join(`
479
+ `)}function IC(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 d=p?me.join(r,p):r;await X.mkdir(d,{recursive:!0});let m=me.join(d,`${t}.skill.md`);try{return await X.access(m),JSON.stringify({error:"skill_exists",message:`Skill "${t}" already exists at ${m}. Use skill.update to modify it.`},null,2)}catch{}let g=OC({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:c});return await X.writeFile(m,g,"utf-8"),JSON.stringify({success:!0,skill:t,path:m,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 mT(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 X.readFile(n,"utf-8")).replace(/\r\n/g,`
480
+ `),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:yt(s,"Description")}:o==="triggers"?{skill:t,triggers:Ji(s)}:o==="instructions"?{skill:t,instructions:yt(s,"Instructions")}:o==="examples"?{skill:t,examples:yt(s,"Examples")}:{skill:t,path:n,metadata:a,description:yt(s,"Description"),triggers:Ji(s),instructions:yt(s,"Instructions"),examples:yt(s,"Examples")||void 0},null,2)}}}function LC(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 mT(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 d=(await X.readFile(p,"utf-8")).replace(/\r\n/g,`
481
+ `),m=Vi(d),g=m.tags?Qi(m.tags):[],T=m.title||t,y=m.version||"1.0.0",w=o??T,k=c?[...new Set([...g,...c])]:g,C=new Date().toISOString();if(n!==void 0&&(d=d.replace(/## Description\n\n[\s\S]*?(?=\n## )/,`## Description
482
482
 
483
483
  ${n}
484
484
 
485
- `)),s!==void 0){let C=s.map(_=>`- "${_}"`).join(`
486
- `);m=m.replace(/## Triggers\n\n[\s\S]*?(?=\n## )/,`## Triggers
485
+ `)),s!==void 0){let v=s.map(P=>`- "${P}"`).join(`
486
+ `);d=d.replace(/## Triggers\n\n[\s\S]*?(?=\n## )/,`## Triggers
487
487
 
488
- ${C}
488
+ ${v}
489
489
 
490
- `)}if(i!==void 0&&(m=m.replace(/## Instructions\n\n[\s\S]*?(?=\n## |$)/,`## Instructions
490
+ `)}if(i!==void 0&&(d=d.replace(/## Instructions\n\n[\s\S]*?(?=\n## |$)/,`## Instructions
491
491
 
492
492
  ${i}
493
493
 
494
- `)),a){let C=m.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if(C){let _=C[1]??"",E=_.trim()?`
494
+ `)),a){let v=d.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if(v){let P=v[1]??"",E=P.trim()?`
495
495
 
496
- `:"";m=m.replace(/## Examples\n\n[\s\S]*?(?=\n## |$)/,`## Examples
496
+ `:"";d=d.replace(/## Examples\n\n[\s\S]*?(?=\n## |$)/,`## Examples
497
497
 
498
- ${_}${E}${a}
498
+ ${P}${E}${a}
499
499
 
500
- `)}else m=m.trimEnd()+`
500
+ `)}else d=d.trimEnd()+`
501
501
 
502
502
  ## Examples
503
503
 
504
504
  ${a}
505
- `}m=m.replace(/^---\n[\s\S]*?\n---/,["---",`name: ${t}`,`title: ${w}`,`version: ${b}`,`updated: ${v}`,`tags: [${k.map(C=>`"${C}"`).join(", ")}]`,"---"].join(`
506
- `)),await V.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 NC(r){return{name:"skill.list",displayName:"List Skills",description:"List all skills in the skill library, optionally filtered by tag.",category:"skills",parameters:{type:"object",properties:{tag:{type:"string",description:"Filter skills by tag (optional)."},verbose:{type:"boolean",description:"Include description and triggers in the output (default: false).",default:!1}},required:[]},async execute(e){let t=e.tag,o=e.verbose??!1;try{await V.access(r)}catch{return JSON.stringify({skills:[],count:0,message:"No skills directory found. Use skill.create to create your first skill."},null,2)}let n=await $C(r);if(n.length===0)return JSON.stringify({skills:[],count:0,message:"No skills found. Use skill.create to create your first skill."},null,2);let s=[];for(let i of n){let a=(await V.readFile(i,"utf-8")).replace(/\r\n/g,`
507
- `),c=Bi(a),p=c.name||ae.basename(i,".skill.md"),m=c.title||p,d=c.tags?zi(c.tags):[];if(t&&!d.includes(t))continue;let g=ae.dirname(ae.relative(r,i)),T=g==="."?void 0:g.split(ae.sep)[0];o?s.push({name:p,title:m,tags:d,category:T,description:pt(a,"Description")||void 0,triggers:Gi(a)}):s.push({name:p,title:m})}return JSON.stringify({skills:s,count:s.length,filtered:t?`by tag: ${t}`:null},null,2)}}}function OC(r){let e=ae.resolve(r?.dir??".toolpack/skills"),t=[DC(e),MC(e),AC(e),NC(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 Hi=`
505
+ `}d=d.replace(/^---\n[\s\S]*?\n---/,["---",`name: ${t}`,`title: ${w}`,`version: ${y}`,`updated: ${C}`,`tags: [${k.map(v=>`"${v}"`).join(", ")}]`,"---"].join(`
506
+ `)),await X.writeFile(p,d,"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 FC(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 X.access(r)}catch{return JSON.stringify({skills:[],count:0,message:"No skills directory found. Use skill.create to create your first skill."},null,2)}let n=await NC(r);if(n.length===0)return JSON.stringify({skills:[],count:0,message:"No skills found. Use skill.create to create your first skill."},null,2);let s=[];for(let i of n){let a=(await X.readFile(i,"utf-8")).replace(/\r\n/g,`
507
+ `),c=Vi(a),p=c.name||me.basename(i,".skill.md"),d=c.title||p,m=c.tags?Qi(c.tags):[];if(t&&!m.includes(t))continue;let g=me.dirname(me.relative(r,i)),T=g==="."?void 0:g.split(me.sep)[0];o?s.push({name:p,title:d,tags:m,category:T,description:yt(a,"Description")||void 0,triggers:Ji(a)}):s.push({name:p,title:d})}return JSON.stringify({skills:s,count:s.length,filtered:t?`by tag: ${t}`:null},null,2)}}}function qC(r){let e=me.resolve(r?.dir??".toolpack/skills"),t=[IC(e),jC(e),LC(e),FC(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=`
508
508
  You are a planning assistant. Given a user request, create a detailed step-by-step plan.
509
509
 
510
510
  Rules:
@@ -530,7 +530,7 @@ Rules:
530
530
  }
531
531
  ]
532
532
  }
533
- `,hG={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},aT={name:"Agent",planning:{enabled:!0,planningPrompt:Hi},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},IC=`
533
+ `,kG={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},dT={name:"Agent",planning:{enabled:!0,planningPrompt:Xi},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},WC=`
534
534
  Create a step-by-step plan for this coding task.
535
535
 
536
536
  Rules:
@@ -553,7 +553,7 @@ JSON Schema:
553
553
  }
554
554
  ]
555
555
  }
556
- `,lT={name:"Coding",planning:{enabled:!0,planningPrompt:IC},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},cT={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var pT={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:aT,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},mT={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:["http","web"],blockedToolCategories:["filesystem","execution","system","coding","git","database"],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!1,includeToolCategories:!0},workflow:cT,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},dT={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:lT,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"]}},$r=[pT,dT,mT],Mt="chat";var yn=class{modes=new Map;orderedNames=[];constructor(){for(let e of $r)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(Mt);if(!e)throw new Error(`Default mode "${Mt}" 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($r.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 jC(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,rulesDir:r.rulesDir,streaming:r.streaming}}l();var Ki={planning:{enabled:!1},progress:{enabled:!0}};l();S();var LC=Hi,bn=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||LC,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 FC}from"events";S();var Er=class extends FC{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new bt,this.planner=new bn(e,t.planning)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new bn(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=Ye(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
+ `,uT={name:"Coding",planning:{enabled:!0,planningPrompt:WC},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},fT={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var gT={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:dT,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},hT={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:["http","web"],blockedToolCategories:["filesystem","execution","system","coding","git","database"],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!1,includeToolCategories:!0},workflow:fT,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},yT={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:uT,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=[gT,yT,hT],It="chat";var xn=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(It);if(!e)throw new Error(`Default mode "${It}" 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 UC(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,rulesDir:r.rulesDir,streaming:r.streaming}}l();var Yi={planning:{enabled:!1},progress:{enabled:!0}};l();_();var GC=Xi,vn=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||GC,n=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);b(`[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),d=this.parsePlan(p.content||"",e,p);return S(`[Planner] createPlan() succeeded plan.id=${d.id} steps=${d.steps.length}`),d}catch(p){return M(`[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&&M(`[Planner] parsePlan() truncated ${n.steps.length} steps to maxSteps=${s}`),b(`[Planner] parsePlan() parsed ${i.length} steps successfully`);let a=i.map((p,d)=>({id:`step-${Date.now()}-${d}`,number:p.number||d+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 M(`[Planner] parsePlan() failed: ${n.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){M("[Planner] createFallbackPlan() \u2014 creating single-step fallback due to plan generation failure");let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}-fallback`,request:t,summary:"Fallback single-step plan due to generation failure",steps:[{id:"step-1",number:1,description:"Execute the user request",status:"pending",expectedTools:[],dependsOn:[]}],status:"draft",createdAt:new Date}}};l();import{EventEmitter as BC}from"events";_();var Nr=class extends BC{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new Ct,this.planner=new vn(e,t.planning)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new vn(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=rt(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 b(`[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(b(`[Workflow] execute() planningEnabled=${o} provider=${t??"default"}`),!o)return b("[Workflow] execute() mode=direct"),this.executeDirect(e,t);b("[Workflow] execute() mode=plan-direct \u2014 creating plan");let n=await this.createPlan(e,t);if(this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){S(`[Workflow] Plan "${n.id}" requires approval \u2014 waiting`),this.emitProgress(n,"awaiting_approval","Waiting for plan approval");let s=await this.waitForApproval(n.id);if(this.emit("workflow:plan_decision",n,s),!s)return S(`[Workflow] Plan "${n.id}" rejected by user`),n.status="cancelled",this.emitProgress(n,"failed","Plan rejected by user"),{success:!1,plan:n,error:"Plan rejected by user",metrics:{totalDuration:0,stepsCompleted:0,stepsFailed:0,retriesUsed:0}};S(`[Workflow] Plan "${n.id}" approved`)}return n.status="approved",this.executePlanDirect(n,e,t)}async executeDirect(e,t){let o=Date.now(),n=this.createDummyPlan(e);b(`[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;b(`[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",M(`[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){b(`[Workflow] createPlan() provider=${t??"default"}`);let o=this.createDummyPlan(e);o.status="draft",this.emitProgress(o,"planning","Creating plan...");let n=await this.planner.createPlan(e,t);return S(`[Workflow] createPlan() completed plan.id=${n.id} steps=${n.steps.length}`),n}async executePlanDirect(e,t,o){let n=Date.now();e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),this.emitProgress(e,"executing","Executing plan",10),b(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
557
557
  You have created the following plan to fulfill the request:
558
558
  Summary: ${e.summary}
559
559
 
@@ -562,12 +562,12 @@ ${e.steps.map(c=>`${c.number}. ${c.description}`).join(`
562
562
  `)}
563
563
 
564
564
  Execute this plan now.
565
- `.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
+ `.trim(),i=this.injectPlanContext(t.messages,s),a={...t,messages:i};try{let c=await this.client.generate(a,o);e.steps.forEach(d=>{d.status="completed",d.result={success:!0,output:c.content||"",response:c}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,n,0),b(`[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,M(`[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(`
566
566
  `);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}
567
567
 
568
568
  ---
569
569
 
570
- ${s}`},...e.slice(1)]}return[{role:"system",content:t},...e]}async*stream(e,t){if(this.shouldRouteSimpleQuery(e)){y("[Workflow] stream() complexity-routed \u2192 direct"),yield*this.streamDirect(e,t);return}let o=this.config.planning?.enabled;if(y(`[Workflow] stream() planningEnabled=${o} provider=${t??"default"}`),!o){y("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}yield{delta:"",workflowStep:{number:0,description:"Creating plan..."}};let n=await this.planner.createPlan(e,t);if(this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){this.emitProgress(n,"awaiting_approval","Waiting for plan approval"),yield{delta:`
570
+ ${s}`},...e.slice(1)]}return[{role:"system",content:t},...e]}async*stream(e,t){if(this.shouldRouteSimpleQuery(e)){b("[Workflow] stream() complexity-routed \u2192 direct"),yield*this.streamDirect(e,t);return}let o=this.config.planning?.enabled;if(b(`[Workflow] stream() planningEnabled=${o} provider=${t??"default"}`),!o){b("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}yield{delta:"",workflowStep:{number:0,description:"Creating plan..."}};let n=await this.planner.createPlan(e,t);if(this.emit("workflow:plan_created",n),this.config.planning?.requireApproval){this.emitProgress(n,"awaiting_approval","Waiting for plan approval"),yield{delta:`
571
571
 
572
572
  **Plan Created:**
573
573
  ${n.summary}
@@ -587,8 +587,8 @@ ${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
587
587
  `)}
588
588
 
589
589
  Execute this plan now.
590
- `.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 wT}from"events";S();var xT=class r extends wT{client;activeProviderName;modeRegistry;workflowExecutor;knowledgeLayers=[];customProviderNames=new Set;mcpToolProject=null;_interceptors=[];_instanceRequestTools=[];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 Er(this.client,Ki,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."})}]}registerRequestTools(e){for(let t of e){let o=this._instanceRequestTools.findIndex(n=>n.name===t.name);o>=0?this._instanceRequestTools[o]=t:this._instanceRequestTools.push(t)}}prepareRequest(e){let t=[...this._instanceRequestTools,...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){ka(e.logging);let t=new gn,o={...oe,...e.toolsConfig||{}};t.setConfig(o),e.tools&&await t.loadBuiltIn(),e.toolOverrides?.length&&await t.loadProjects(e.toolOverrides);let n=null,s=e.mcp;if(s)try{P("[MCP] Initializing MCP tool integration");let x=await Wi(s);n=x,await t.loadProjects([x]),P(`[MCP] Loaded ${x.tools.length} tools from MCP servers`)}catch(x){pe(`[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 yn;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 vn({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}),T=new r(g,p,m),b=e.knowledge,w=b==null?[]:Array.isArray(b)?b:[b];T.knowledgeLayers=w.filter(x=>!!x&&typeof x.toTool=="function"),T.registerRequestTools(T._buildKnowledgeRequestTools()),T.customProviderNames=c,T.mcpToolProject=n,T._interceptors=e.interceptors??[];for(let x of T._interceptors)x.init&&await x.init();let k=e.defaultMode||Mt,v=m.get(k);return v&&(g.setMode(v),v.workflow&&T.workflowExecutor.setConfig(v.workflow)),T}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new Sn({projectId:t.projectId,location:t.location,googleAuthOptions:t.googleAuthOptions,thinkingBudget:t.thinkingBudget});if(e==="anthropic-vertex")return new kn({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 vt(i,t.baseUrl);case"anthropic":return new Cn(i,t.baseUrl);case"gemini":return new Pn(i);case"openrouter":return new $n(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new Ut({baseUrl:t.baseUrl||Rn(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||Rn(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=Wt(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 Ui(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){return this.loadToolProjects([e])}async loadToolProjects(e){let t=this.client.getToolRegistry();if(!t)throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.");for(let o of e)await t.loadProject(o);this.client.reindexTools()}loadRequestToolProject(e){this.registerRequestTools(e.tools)}searchTools(e,t){let o=this.client.executeToolSearch({query:e,...t?{category:t}:{}});return JSON.parse(o)}getRegisteredToolNames(){return this.client.getToolRegistry()?.getNames()??[]}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(()=>(TT(),bT))).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:
591
- 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(Ki),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 wT&&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 Dr=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 Xi=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new Dr(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 ZC from"better-sqlite3";import*as At from"fs";import*as Tn from"path";function ek(){let r=Tn.join(process.cwd(),".toolpack","db","conversation");return At.existsSync(r)||At.mkdirSync(r,{recursive:!0}),Tn.join(r,"conversation.sqlite")}var Yi=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??ek(),o=Tn.dirname(t);if(At.existsSync(o)||At.mkdirSync(o,{recursive:!0}),this.db=new ZC(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(`
590
+ `.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 ST}from"events";_();var _T=class r extends ST{client;activeProviderName;modeRegistry;workflowExecutor;knowledgeLayers=[];customProviderNames=new Set;mcpToolProject=null;_interceptors=[];_instanceRequestTools=[];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 Nr(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(m=>({...m,_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."})}]}registerRequestTools(e){for(let t of e){let o=this._instanceRequestTools.findIndex(n=>n.name===t.name);o>=0?this._instanceRequestTools[o]=t:this._instanceRequestTools.push(t)}}prepareRequest(e){let t=[...this._instanceRequestTools,...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){$a(e.logging);let t=new Tn,o={...se,...e.toolsConfig||{}};t.setConfig(o),e.tools&&await t.loadBuiltIn(),e.toolOverrides?.length&&await t.loadProjects(e.toolOverrides);let n=null,s=e.mcp;if(s)try{S("[MCP] Initializing MCP tool integration");let v=await Hi(s);n=v,await t.loadProjects([v]),S(`[MCP] Loaded ${v.tools.length} tools from MCP servers`)}catch(v){ue(`[MCP] Failed to initialize MCP tools: ${v}`)}let i=e.disableBaseContext??!1,a=e.disableToolGuidance??!1,c={},p=new Set,d=e.defaultProvider||e.provider;if(e.providers)for(let[v,P]of Object.entries(e.providers)){let E=v===d,j=await r.createProvider(v,P,void 0,!E);j&&(c[v]=j)}else if(e.provider){let v={apiKey:e.apiKey,model:e.model,projectId:e.projectId,location:e.location,googleAuthOptions:e.googleAuthOptions,thinkingBudget:e.thinkingBudget,region:e.region},P=await r.createProvider(e.provider,v,void 0,!1);P&&(c[e.provider]=P)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let v=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([P,E])=>(E.name=E.name||P,E));for(let P of v){if(typeof P.generate!="function"||typeof P.stream!="function"||typeof P.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let E=P.name;if(!E)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(c[E])throw new Error(`Custom provider name "${E}" conflicts with a built-in provider designation. Choose a different name.`);p.add(E),c[E]=P}}if(!d&&e.customProviders&&(d=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!d)throw new Error("No default provider specified.");let m=new xn;if(e.customModes)for(let v of e.customModes)m.register(v);let g={...e.hitl||{}};e.confirmationMode!==void 0&&(g.confirmationMode=e.confirmationMode),g.enabled===void 0&&e.onToolConfirm&&(g.enabled=!0),g.confirmationMode===void 0&&e.onToolConfirm&&(g.confirmationMode="all");let T=new _n({providers:c,defaultProvider:d,toolRegistry:t,toolsConfig:t.getConfig(),disableBaseContext:i,disableToolGuidance:a,hitlConfig:Object.keys(g).length>0?g:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow,actor:e.actor}),y=new r(T,d,m),w=e.knowledge,k=w==null?[]:Array.isArray(w)?w:[w];y.knowledgeLayers=k.filter(v=>!!v&&typeof v.toTool=="function"),y.registerRequestTools(y._buildKnowledgeRequestTools()),y.customProviderNames=p,y.mcpToolProject=n,y._interceptors=e.interceptors??[];for(let v of y._interceptors)v.init&&await v.init();let C=e.defaultMode||It,x=m.get(C);return x&&(T.setMode(x),x.workflow&&y.workflowExecutor.setConfig(x.workflow)),y}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new $n({projectId:t.projectId,location:t.location,googleAuthOptions:t.googleAuthOptions,thinkingBudget:t.thinkingBudget});if(e==="anthropic-vertex")return new Rn({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 _t(i,t.baseUrl);case"anthropic":return new Pn(i,t.baseUrl);case"gemini":return new En(i);case"openrouter":return new Mn(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new Ht({baseUrl:t.baseUrl||An(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||An(o);return new ct({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 m of s.plan.steps)if(m.status==="completed"&&m.result?.response?.usage){let g=m.result.response.usage;i+=g.prompt_tokens,a+=g.completion_tokens||0,c+=g.total_tokens,p.steps.push({stepNumber:m.number,description:m.description,usage:g})}let d={prompt_tokens:i,completion_tokens:a,total_tokens:c};return s.response?{...s.response,content:s.output||s.response.content||null,usage:d,usage_details:p}:{content:s.output||null,usage:d,usage_details:p}}return this._interceptors.length>0?this._buildInterceptorChain(this._interceptors,i=>this.client.generate(i??o,t,{getLatestRequestTools:()=>[...this._instanceRequestTools]}))(o):this.client.generate(o,t,{getLatestRequestTools:()=>[...this._instanceRequestTools]})}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,{getLatestRequestTools:()=>[...this._instanceRequestTools]})}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||lt();if(t)try{let o=zt(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){M(`[Toolpack] Failed to reload config from ${t}: ${o instanceof Error?o.message:String(o)}`)}}getWorkflowExecutor(){return this.workflowExecutor}async disconnect(){let e=this.getProvider();e&&"disconnect"in e&&await e.disconnect(),this.mcpToolProject&&await 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){M(`[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){return this.loadToolProjects([e])}async loadToolProjects(e){let t=this.client.getToolRegistry();if(!t)throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.");for(let o of e)await t.loadProject(o);this.client.reindexTools()}loadRequestToolProject(e){this.registerRequestTools(e.tools)}searchTools(e,t){let o=this.client.executeToolSearch({query:e,...t?{category:t}:{}});return JSON.parse(o)}getRegisteredToolNames(){return this.client.getToolRegistry()?.getNames()??[]}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(()=>(kT(),CT))).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:
591
+ 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 ST&&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 Or=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 Or(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(m=>m.content.toLowerCase().includes(s)).slice().reverse(),p=[],d=0;for(let m of c){if(p.length>=i)break;let g=Math.ceil(m.content.length/4);if(p.length>0&&d+g>a)break;p.push(m),d+=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 rk from"better-sqlite3";import*as jt from"fs";import*as Cn from"path";function sk(){let r=Cn.join(process.cwd(),".toolpack","db","conversation");return jt.existsSync(r)||jt.mkdirSync(r,{recursive:!0}),Cn.join(r,"conversation.sqlite")}var na=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??sk(),o=Cn.dirname(t);if(jt.existsSync(o)||jt.mkdirSync(o,{recursive:!0}),this.db=new rk(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(`
592
592
  CREATE TABLE IF NOT EXISTS messages (
593
593
  id TEXT NOT NULL,
594
594
  conversation_id TEXT NOT NULL,
@@ -603,7 +603,7 @@ Execute this plan now.
603
603
  )`),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 (
604
604
  id, conversation_id, participant_kind, participant_id, participant_display_name,
605
605
  content, timestamp, scope, metadata
606
- ) 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 T=m.map(k=>`${e.conversationId}:${k}`),b=T.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${b})`).run(...T)}}}}}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
+ ) 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,d=this.db.prepare("SELECT id FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC LIMIT ?").all(e.conversationId,c).map(m=>m.id);if(d.length>0){let m=d.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${m})`).run(e.conversationId,...d),this.useFTS){let T=d.map(k=>`${e.conversationId}:${k}`),y=T.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${y})`).run(...T)}}}}}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(`
607
607
  SELECT m.id, m.conversation_id, m.participant_kind, m.participant_id, m.participant_display_name,
608
608
  m.content, m.timestamp, m.scope, m.metadata
609
609
  FROM messages m
@@ -614,6 +614,6 @@ Execute this plan now.
614
614
  content, timestamp, scope, metadata
615
615
  FROM messages
616
616
  WHERE conversation_id = ? AND content LIKE ? COLLATE NOCASE
617
- 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 vT from"os";import*as mt from"path";import*as Nt from"fs";var CT=".toolpack",kT="config",ST="toolpack.config.json";function tk(){return vT.homedir()}function ok(){return mt.join(tk(),CT)}function PT(){return mt.join(ok(),kT)}function Mr(){return mt.join(PT(),ST)}function nk(r=process.cwd()){return mt.join(r,CT)}function _T(r=process.cwd()){return mt.join(nk(r),kT)}function Ar(r=process.cwd()){return mt.join(_T(r),ST)}function RT(){let r=PT();Nt.existsSync(r)||Nt.mkdirSync(r,{recursive:!0})}function qB(r=process.cwd()){let e=_T(r);Nt.existsSync(e)||Nt.mkdirSync(e,{recursive:!0})}l();import*as le from"fs";import*as Nr from"path";function ea(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]=ea(r[o],e[o]):t[o]=e[o];return t}function Zi(r){if(!le.existsSync(r))return null;try{let e=le.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function zB(r=process.cwd()){let e=Nr.join(r,"toolpack.config.json"),t=Mr(),o=Ar(r),n=Zi(e)||{},s=Zi(t)||{},i=Zi(o)||{},a=ea(n,s);return a=ea(a,i),a}function HB(r=process.cwd()){let e=Nr.join(r,"toolpack.config.json"),t=Mr(),o=Ar(r),n=!le.existsSync(t),s=null,i="default";return le.existsSync(o)?(s=o,i="local"):le.existsSync(t)?(s=t,i="global"):le.existsSync(e)&&(s=e,i="base"),{isFirstRun:n,activeConfigPath:s,configSource:i}}function KB(r=process.cwd()){let e=Mr();if(!le.existsSync(e)){RT();let t=null,o=Ar(r);if(le.existsSync(o))t=o;else{let s=Nr.join(r,"toolpack.config.json");if(le.existsSync(s))t=s;else{let i=tt();i&&le.existsSync(i)&&(t=i)}}let n={};if(t)try{let s=le.readFileSync(t,"utf-8");n=JSON.parse(s)}catch{}le.writeFileSync(e,JSON.stringify(n,null,4),"utf-8")}}l();l();var rk=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"]),ta=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=>!rk.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 T=this.idf(m),b=g*(this.k1+1),w=g+this.k1*(1-this.b+this.b*(p/this.avgDocLength));c+=T*(b/w)}c>0&&(n[a]=c)});let s=Object.entries(n).map(([i,a])=>({id:i,score:a}));return s.sort((i,a)=>a.score-i.score),s.slice(0,t)}};l();import*as Je from"path";function sk(r,e,t){let o=r.match(/^---\n([\s\S]*?)\n---/),n="",s="",i,a=[];if(o&&o[1]){let C=o[1].split(`
618
- `),_=!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 ee=E.substring(0,$).trim(),F=E.substring($+1).trim();if(ee==="name"&&(n=F),ee==="title"&&(s=F),ee==="version"&&(i=F),ee==="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(`
619
- `).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## |$)/),T=g&&g[1]?g[1].trim():"",b=r.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/),w=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:T,examples:w||void 0,lastModified:0}}export{pT as AGENT_MODE,Hi as AGENT_PLANNING_PROMPT,aT as AGENT_WORKFLOW,vn as AIClient,Cn as AnthropicAdapter,kn as AnthropicVertexAdapter,fe as AuthenticationError,ta as BM25Engine,Lt as BM25SearchEngine,$r as BUILT_IN_MODES,mT as CHAT_MODE,cT as CHAT_WORKFLOW,dT as CODING_MODE,IC as CODING_PLANNING_PROMPT,lT as CODING_WORKFLOW,kT as CONFIG_DIR_NAME,ST as CONFIG_FILE_NAME,Ve as ConnectionError,ia as ContextWindowConfigError,Or as ContextWindowExceededError,Ur as ContextWindowStateManager,aa as ConversationNotFoundError,Mt as DEFAULT_MODE_NAME,oe as DEFAULT_TOOLS_CONFIG,zT as DEFAULT_TOOL_SEARCH_CONFIG,hG as DEFAULT_WORKFLOW,Ki as DEFAULT_WORKFLOW_CONFIG,pk as FILE_LIMITS,Pn as GeminiAdapter,Xi as InMemoryConversationStore,Ir as InsufficientContextError,M as InvalidRequestError,hn as McpClient,Ne as McpConnectionError,_r as McpTimeoutError,Rr as McpToolManager,yn as ModeRegistry,ot as OllamaAdapter,Ut as OllamaProvider,vt as OpenAIAdapter,$n as OpenRouterAdapter,ra as PageError,bn as Planner,Z as ProviderAdapter,I as ProviderError,se as RateLimitError,wt as RuleLoader,N as SDKError,Yi as SQLiteConversationStore,jr as SummarizationError,CT as TOOLPACK_DIR_NAME,Qe as TOOL_SEARCH_NAME,sa as TimeoutError,ht as ToolDiscoveryCache,gn as ToolRegistry,qt as ToolRouter,xT as Toolpack,Sn as VertexAIAdapter,Er as WorkflowExecutor,fw as addBypassRule,Nk as buildSummarizedHistory,dr as cloudDeployTool,fr as cloudListTool,ur as cloudStatusTool,ub as cloudToolsProject,sn as codingExtractFunctionTool,Yo as codingFindReferencesTool,Vo as codingFindSymbolTool,an as codingGetCallHierarchyTool,nn as codingGetDiagnosticsTool,rn as codingGetExportsTool,Xo as codingGetImportsTool,on as codingGetOutlineTool,Qo as codingGetSymbolsTool,Zo as codingGoToDefinitionTool,en as codingMultiFileEditTool,tn as codingRefactorRenameTool,Oh as codingToolsProject,pa as countTokens,ha as createContextWindowStateManager,Wi as createMcpToolProject,jC as createMode,OC as createSkillTools,Ok as createSummarizationReport,Wr as createSummarySystemMessage,PC as createToolProject,pr as dbCountTool,cr as dbDeleteTool,ar as dbInsertTool,rr as dbQueryTool,sr as dbSchemaTool,ir as dbTablesTool,ob as dbToolsProject,lr as dbUpdateTool,Zn as diffApplyTool,Yn as diffCreateTool,er as diffPreviewTool,$y as diffToolsProject,Ui as disconnectMcpToolProject,RT as ensureGlobalConfigDir,qB as ensureLocalConfigDir,UT as estimateSummaryTokens,je as estimateTokenCount,bo as execKillTool,To as execListProcessesTool,ho as execReadOutputTool,fo as execRunBackgroundTool,go as execRunBlockingTool,uo as execRunShellTool,mo as execRunTool,yo as execTailOutputTool,sm as execToolsProject,Ak as extractConversationKeypoints,Oa as fetchUrlAsBase64,Jt as fsAppendFileTool,co as fsBatchReadTool,po as fsBatchWriteTool,oo as fsCopyTool,Zt as fsCreateDirTool,lo as fsDeleteDirTool,Vt as fsDeleteFileTool,Qt as fsExistsTool,ao as fsGlobTool,Yt as fsListDirTool,eo as fsMoveTool,no as fsReadFileRangeTool,Ht as fsReadFileTool,so as fsReplaceInFileTool,ro as fsSearchTool,Xt as fsStatTool,cp as fsToolsProject,io as fsTreeTool,Kt as fsWriteFileTool,WT as generateSummarizationPrompt,Gr as generateToolCategoriesPrompt,kk as getContextWindowPercentage,hw as getDefaultSlmModel,PT as getGlobalConfigDir,Mr as getGlobalConfigPath,ok as getGlobalToolpackDir,_T as getLocalConfigDir,Ar as getLocalConfigPath,nk as getLocalToolpackDir,$k as getMessageStats,Da as getMimeType,Rn as getOllamaBaseUrl,uw as getOllamaProviderEntries,bw as getRegisteredSlmModels,HB as getRuntimeConfigStatus,ma as getSafeOutputReserve,Xe as getToolSearchSchema,Jr as getToolpackConfig,tk as getUserHomeDir,Bn as gitAddTool,Hn as gitBlameTool,Jn as gitBranchCreateTool,Kn as gitBranchListTool,Vn as gitCheckoutTool,Xn as gitCloneTool,zn as gitCommitTool,Un as gitDiffTool,Gn as gitLogTool,Wn as gitStatusTool,fy as gitToolsProject,Do as githubContentsGetTextTool,Eo as githubGraphqlExecuteTool,Lo as githubIssuesCommentsCreateTool,Oo as githubPrDiffGetTool,Io as githubPrFilesListTool,No as githubPrReviewCommentsReplyTool,Mo as githubPrReviewThreadsListTool,Ao as githubPrReviewThreadsResolveTool,jo as githubPrReviewsSubmitTool,Su as githubToolsProject,Rk as groupMessagesByRole,fk as handleContextWindowError,Ro as httpDeleteTool,$o as httpDownloadTool,So as httpGetTool,Po as httpPostTool,_o as httpPutTool,Cd as httpToolsProject,KB as initializeGlobalConfigIfFirstRun,uk as isContextWindowError,Ma as isDataUri,yw as isRegisteredSlm,yt as isToolSearchTool,br as k8sApplyManifestTool,Tr as k8sDeleteResourceTool,hr as k8sDescribeTool,vr as k8sGetConfigMapTool,yr as k8sGetLogsTool,kr as k8sGetNamespacesTool,xr as k8sListDeploymentsTool,gr as k8sListPodsTool,wr as k8sListServicesTool,Cr as k8sSwitchContextTool,tT as k8sToolsProject,Sr as k8sWaitForDeploymentTool,rT as loadFullConfig,zB as loadRuntimeConfig,CC as loadToolsConfig,Ik as mergeSummarizationResults,iw as normalizeImagePart,_e as ollamaRequest,Vr as ollamaStream,Aa as parseDataUri,sk as parseSkillFile,ga as parseSummarizationResponse,fa as prepareSummarizationRequest,da as pruneMessages,Na as readFileAsBase64,dw as reloadToolpackConfig,gw as removeBypassRule,kC as saveToolsConfig,fn as slackAuthTestTool,pn as slackChatPostEphemeralTool,cn as slackChatPostMessageTool,dn as slackConversationsHistoryTool,un as slackConversationsRepliesTool,mn as slackReactionsAddTool,Xb as slackToolsProject,Co as systemCwdTool,ko as systemDiskUsageTool,xo as systemEnvTool,wo as systemInfoTool,vo as systemSetEnvTool,qm as systemToolsProject,sw as toDataUri,Le as toolSearchDefinition,_k as truncateMessage,ua as validateSummarizationResult,Uo as webExtractLinksTool,Ho as webFeedTool,Fo as webFetchTool,Go as webMapTool,Bo as webMetadataTool,Wo as webScrapeTool,Ko as webScreenshotTool,qo as webSearchTool,zo as webSitemapTool,Hf as webToolsProject,Ck as wouldExceedContextWindow};
617
+ ORDER BY timestamp DESC`).all(e,`%${t}%`);let a=i.map(d=>this.rowToMessage(d)),c=[],p=0;for(let d of a){if(c.length>=n)break;let m=Math.ceil(d.content.length/4);if(c.length>0&&p+m>s)break;c.push(d),p+=m}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 PT from"os";import*as bt from"path";import*as Lt from"fs";var RT=".toolpack",$T="config",ET="toolpack.config.json";function ik(){return PT.homedir()}function ak(){return bt.join(ik(),RT)}function DT(){return bt.join(ak(),$T)}function Ir(){return bt.join(DT(),ET)}function lk(r=process.cwd()){return bt.join(r,RT)}function AT(r=process.cwd()){return bt.join(lk(r),$T)}function jr(r=process.cwd()){return bt.join(AT(r),ET)}function MT(){let r=DT();Lt.existsSync(r)||Lt.mkdirSync(r,{recursive:!0})}function JB(r=process.cwd()){let e=AT(r);Lt.existsSync(e)||Lt.mkdirSync(e,{recursive:!0})}l();import*as de 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(!de.existsSync(r))return null;try{let e=de.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function ZB(r=process.cwd()){let e=Lr.join(r,"toolpack.config.json"),t=Ir(),o=jr(r),n=ra(e)||{},s=ra(t)||{},i=ra(o)||{},a=sa(n,s);return a=sa(a,i),a}function e2(r=process.cwd()){let e=Lr.join(r,"toolpack.config.json"),t=Ir(),o=jr(r),n=!de.existsSync(t),s=null,i="default";return de.existsSync(o)?(s=o,i="local"):de.existsSync(t)?(s=t,i="global"):de.existsSync(e)&&(s=e,i="base"),{isFirstRun:n,activeConfigPath:s,configSource:i}}function t2(r=process.cwd()){let e=Ir();if(!de.existsSync(e)){MT();let t=null,o=jr(r);if(de.existsSync(o))t=o;else{let s=Lr.join(r,"toolpack.config.json");if(de.existsSync(s))t=s;else{let i=lt();i&&de.existsSync(i)&&(t=i)}}let n={};if(t)try{let s=de.readFileSync(t,"utf-8");n=JSON.parse(s)}catch{}de.writeFileSync(e,JSON.stringify(n,null,4),"utf-8")}}l();l();var ck=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"]),ia=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=>!ck.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 d of o){let m=this.termFrequencies.get(d);if(!m)continue;let g=m.get(a)??0;if(g===0)continue;let T=this.idf(d),y=g*(this.k1+1),w=g+this.k1*(1-this.b+this.b*(p/this.avgDocLength));c+=T*(y/w)}c>0&&(n[a]=c)});let s=Object.entries(n).map(([i,a])=>({id:i,score:a}));return s.sort((i,a)=>a.score-i.score),s.slice(0,t)}};l();import*as et from"path";function pk(r,e,t){let o=r.match(/^---\n([\s\S]*?)\n---/),n="",s="",i,a=[];if(o&&o[1]){let v=o[1].split(`
618
+ `),P=!1;for(let E of v){if(P){let B=E.match(/^\s+-\s+(.+?)\s*$/);if(B){a.push(B[1].replace(/^["']|["']$/g,""));continue}P=!1}let j=E.indexOf(":");if(j===-1)continue;let R=E.substring(0,j).trim(),te=E.substring(j+1).trim();if(R==="name"&&(n=te),R==="title"&&(s=te),R==="version"&&(i=te),R==="tags")if(te){let B=te.match(/\[([^\]]*)\]/);B&&(a=B[1].split(",").map(Y=>Y.trim().replace(/^["']|["']$/g,"")).filter(Boolean))}else P=!0,a=[]}}n||(n=et.basename(e,".skill.md"));let c=r.match(/## Description\n\n([\s\S]*?)(?=\n## |$)/),p=c&&c[1]?c[1].trim():"",d=r.match(/## Triggers\n\n([\s\S]*?)(?=\n## |$)/),m=[];if(d&&d[1]){let v=d[1].split(`
619
+ `).filter(P=>P.startsWith("- "));for(let P of v){let E=P.match(/^- "(.*)"/);E&&E[1]&&m.push(E[1])}}let g=r.match(/## Instructions\n\n([\s\S]*?)(?=\n## |$)/),T=g&&g[1]?g[1].trim():"",y=r.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/),w=y&&y[1]?y[1].trim():void 0,k=et.relative(t,e),C=et.dirname(k),x=C==="."?void 0:C.split(et.sep)[0];return{name:n,title:s,version:i,tags:a,category:x,filePath:e,description:p,triggers:m,instructions:T,examples:w||void 0,lastModified:0}}export{gT as AGENT_MODE,Xi as AGENT_PLANNING_PROMPT,dT as AGENT_WORKFLOW,_n as AIClient,Pn as AnthropicAdapter,Rn as AnthropicVertexAdapter,ye as AuthenticationError,ia as BM25Engine,Ut as BM25SearchEngine,Mr as BUILT_IN_MODES,hT as CHAT_MODE,fT as CHAT_WORKFLOW,yT as CODING_MODE,WC as CODING_PLANNING_PROMPT,uT as CODING_WORKFLOW,$T as CONFIG_DIR_NAME,ET as CONFIG_FILE_NAME,tt as ConnectionError,ma as ContextWindowConfigError,Fr as ContextWindowExceededError,Hr as ContextWindowStateManager,da as ConversationNotFoundError,It as DEFAULT_MODE_NAME,se as DEFAULT_TOOLS_CONFIG,QT as DEFAULT_TOOL_SEARCH_CONFIG,kG as DEFAULT_WORKFLOW,Yi as DEFAULT_WORKFLOW_CONFIG,gk as FILE_LIMITS,En as GeminiAdapter,oa as InMemoryConversationStore,qr as InsufficientContextError,N as InvalidRequestError,wn as McpClient,Le as McpConnectionError,Dr as McpTimeoutError,Ar as McpToolManager,xn as ModeRegistry,ct as OllamaAdapter,Ht as OllamaProvider,_t as OpenAIAdapter,Mn as OpenRouterAdapter,ca as PageError,vn as Planner,ee as ProviderAdapter,L as ProviderError,ce as RateLimitError,kt as RuleLoader,I as SDKError,na as SQLiteConversationStore,Wr as SummarizationError,RT as TOOLPACK_DIR_NAME,ot as TOOL_SEARCH_NAME,pa as TimeoutError,xt as ToolDiscoveryCache,Tn as ToolRegistry,Bt as ToolRouter,_T as Toolpack,$n as VertexAIAdapter,Nr as WorkflowExecutor,Tw as addBypassRule,Fk as buildSummarizedHistory,hr as cloudDeployTool,br as cloudListTool,yr as cloudStatusTool,bb as cloudToolsProject,pn as codingExtractFunctionTool,on as codingFindReferencesTool,Zo as codingFindSymbolTool,mn as codingGetCallHierarchyTool,ln as codingGetDiagnosticsTool,cn as codingGetExportsTool,tn as codingGetImportsTool,an as codingGetOutlineTool,en as codingGetSymbolsTool,nn as codingGoToDefinitionTool,rn as codingMultiFileEditTool,sn as codingRefactorRenameTool,qh as codingToolsProject,ga as countTokens,xa as createContextWindowStateManager,Hi as createMcpToolProject,UC as createMode,qC as createSkillTools,qk as createSummarizationReport,zr as createSummarySystemMessage,DC as createToolProject,fr as dbCountTool,ur as dbDeleteTool,mr as dbInsertTool,lr as dbQueryTool,cr as dbSchemaTool,pr as dbTablesTool,ab as dbToolsProject,dr as dbUpdateTool,nr as diffApplyTool,or as diffCreateTool,rr as diffPreviewTool,Ny as diffToolsProject,Ki as disconnectMcpToolProject,MT as ensureGlobalConfigDir,JB as ensureLocalConfigDir,KT as estimateSummaryTokens,Ge as estimateTokenCount,vo as execKillTool,Co as execListProcessesTool,wo as execReadOutputTool,bo as execRunBackgroundTool,To as execRunBlockingTool,yo as execRunShellTool,ho as execRunTool,xo as execTailOutputTool,pm as execToolsProject,Lk as extractConversationKeypoints,qa as fetchUrlAsBase64,Yt as fsAppendFileTool,fo as fsBatchReadTool,go as fsBatchWriteTool,io as fsCopyTool,no as fsCreateDirTool,uo as fsDeleteDirTool,Zt as fsDeleteFileTool,eo as fsExistsTool,mo as fsGlobTool,oo as fsListDirTool,ro as fsMoveTool,ao as fsReadFileRangeTool,Qt as fsReadFileTool,co as fsReplaceInFileTool,lo as fsSearchTool,to as fsStatTool,fp as fsToolsProject,po as fsTreeTool,Xt as fsWriteFileTool,HT as generateSummarizationPrompt,Kr as generateToolCategoriesPrompt,$k as getContextWindowPercentage,xw as getDefaultSlmModel,DT as getGlobalConfigDir,Ir as getGlobalConfigPath,ak as getGlobalToolpackDir,AT as getLocalConfigDir,jr as getLocalConfigPath,lk as getLocalToolpackDir,Nk as getMessageStats,Ia as getMimeType,An as getOllamaBaseUrl,bw as getOllamaProviderEntries,Cw as getRegisteredSlmModels,e2 as getRuntimeConfigStatus,ha as getSafeOutputReserve,nt as getToolSearchSchema,Zr as getToolpackConfig,ik as getUserHomeDir,Jn as gitAddTool,Qn as gitBlameTool,Yn as gitBranchCreateTool,Xn as gitBranchListTool,Zn as gitCheckoutTool,tr as gitCloneTool,Vn as gitCommitTool,Hn as gitDiffTool,Kn as gitLogTool,zn as gitStatusTool,Ty as gitToolsProject,Oo as githubContentsGetTextTool,No as githubGraphqlExecuteTool,Uo as githubIssuesCommentsCreateTool,Fo as githubPrDiffGetTool,qo as githubPrFilesListTool,Lo as githubPrReviewCommentsReplyTool,Io as githubPrReviewThreadsListTool,jo as githubPrReviewThreadsResolveTool,Wo as githubPrReviewsSubmitTool,Eu as githubToolsProject,Mk as groupMessagesByRole,Tk as handleContextWindowError,Ao as httpDeleteTool,Mo as httpDownloadTool,$o as httpGetTool,Eo as httpPostTool,Do as httpPutTool,Rd as httpToolsProject,t2 as initializeGlobalConfigIfFirstRun,bk as isContextWindowError,ja as isDataUri,vw as isRegisteredSlm,vt as isToolSearchTool,vr as k8sApplyManifestTool,Cr as k8sDeleteResourceTool,wr as k8sDescribeTool,_r as k8sGetConfigMapTool,xr as k8sGetLogsTool,Rr as k8sGetNamespacesTool,Sr as k8sListDeploymentsTool,Tr as k8sListPodsTool,kr as k8sListServicesTool,Pr as k8sSwitchContextTool,iT as k8sToolsProject,$r as k8sWaitForDeploymentTool,cT as loadFullConfig,ZB as loadRuntimeConfig,RC as loadToolsConfig,Wk as mergeSummarizationResults,mw as normalizeImagePart,Ae as ollamaRequest,es as ollamaStream,La as parseDataUri,at as parseFileEnvelope,pk as parseSkillFile,wa as parseSummarizationResponse,Ta as prepareSummarizationRequest,ya as pruneMessages,Fa as readFileAsBase64,yw as reloadToolpackConfig,ww as removeBypassRule,$C as saveToolsConfig,bn as slackAuthTestTool,fn as slackChatPostEphemeralTool,un as slackChatPostMessageTool,hn as slackConversationsHistoryTool,yn as slackConversationsRepliesTool,gn as slackReactionsAddTool,oT as slackToolsProject,Po as systemCwdTool,Ro as systemDiskUsageTool,So as systemEnvTool,ko as systemInfoTool,_o as systemSetEnvTool,zm as systemToolsProject,pw as toDataUri,Be as toolSearchDefinition,Ak as truncateMessage,ba as validateSummarizationResult,Ho as webExtractLinksTool,Qo as webFeedTool,Go as webFetchTool,Ko as webMapTool,Jo as webMetadataTool,zo as webScrapeTool,Xo as webScreenshotTool,Bo as webSearchTool,Vo as webSitemapTool,Xf as webToolsProject,Rk as wouldExceedContextWindow};