toolpack-sdk 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var nx=Object.create;var Pr=Object.defineProperty;var rx=Object.getOwnPropertyDescriptor;var sx=Object.getOwnPropertyNames;var ix=Object.getPrototypeOf,ax=Object.prototype.hasOwnProperty;var g=(r,e)=>()=>(r&&(e=r(r=0)),e);var ee=(r,e)=>{for(var t in e)Pr(r,t,{get:e[t],enumerable:!0})},Al=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of sx(e))!ax.call(r,n)&&n!==t&&Pr(r,n,{get:()=>e[n],enumerable:!(o=rx(e,n))||o.enumerable});return r};var x=(r,e,t)=>(t=r!=null?nx(ix(r)):{},Al(e||!r||!r.__esModule?Pr(t,"default",{value:r,enumerable:!0}):t,r)),lx=r=>Al(Pr({},"__esModule",{value:!0}),r);var l=g(()=>{"use strict"});function px(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 mx(r,e){return r instanceof Er?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof Rr?{shouldRetry:!1,shouldFallback:!0,action:r.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${r.strategy}`}:r instanceof $r?{shouldRetry:!1,shouldFallback:!0,action:"fail",message:"Insufficient context after recovery attempts"}:{shouldRetry:!1,shouldFallback:!1,action:"none",message:"Unknown context window error"}}var O,ue,ie,M,L,He,Ss,_s,Rr,$r,Er,Ps,Rs,pe=g(()=>{"use strict";l();O=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},ue=class extends O{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},ie=class extends O{constructor(t,o,n){super(t,"RATE_LIMIT_ERROR",429,n);this.retryAfter=o;this.name="RateLimitError"}retryAfter},M=class extends O{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},L=class extends O{constructor(e,t="PROVIDER_ERROR",o=500,n){super(e,t,o,n),this.name="ProviderError"}},He=class extends O{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},Ss=class extends O{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},_s=class extends O{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},Rr=class extends O{constructor(t,o,n,s,i,a){super(t,"CONTEXT_WINDOW_EXCEEDED",400,a);this.conversationId=o;this.currentTokens=n;this.contextWindowLimit=s;this.strategy=i;this.name="ContextWindowExceededError"}conversationId;currentTokens;contextWindowLimit;strategy;getOverageTokens(){return Math.max(0,this.currentTokens-this.contextWindowLimit)}getUsagePercentage(){return Math.round(this.currentTokens/this.contextWindowLimit*100)}getDetailedReport(){return`
1
+ "use strict";var ix=Object.create;var Er=Object.defineProperty;var ax=Object.getOwnPropertyDescriptor;var lx=Object.getOwnPropertyNames;var cx=Object.getPrototypeOf,px=Object.prototype.hasOwnProperty;var g=(r,e)=>()=>(r&&(e=r(r=0)),e);var te=(r,e)=>{for(var t in e)Er(r,t,{get:e[t],enumerable:!0})},Ol=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of lx(e))!px.call(r,n)&&n!==t&&Er(r,n,{get:()=>e[n],enumerable:!(o=ax(e,n))||o.enumerable});return r};var x=(r,e,t)=>(t=r!=null?ix(cx(r)):{},Ol(e||!r||!r.__esModule?Er(t,"default",{value:r,enumerable:!0}):t,r)),mx=r=>Ol(Er({},"__esModule",{value:!0}),r);var c=g(()=>{"use strict"});function ux(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 fx(r,e){return r instanceof Mr?{shouldRetry:r.isRetryable(),shouldFallback:!0,action:r.isRetryable()?"prune":"fail",message:r.getSuggestedRecovery()}:r instanceof Dr?{shouldRetry:!1,shouldFallback:!0,action:r.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${r.strategy}`}:r instanceof Ar?{shouldRetry:!1,shouldFallback:!0,action:"fail",message:"Insufficient context after recovery attempts"}:{shouldRetry:!1,shouldFallback:!1,action:"none",message:"Unknown context window error"}}var M,fe,ae,O,F,Je,Rs,$s,Dr,Ar,Mr,Es,Ds,le=g(()=>{"use strict";c();M=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 M{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},ae=class extends M{constructor(t,o,n){super(t,"RATE_LIMIT_ERROR",429,n);this.retryAfter=o;this.name="RateLimitError"}retryAfter},O=class extends M{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},F=class extends M{constructor(e,t="PROVIDER_ERROR",o=500,n){super(e,t,o,n),this.name="ProviderError"}},Je=class extends M{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},Rs=class extends M{constructor(t,o,n){super(t,"PAGE_ERROR",502,n);this.pageUrl=o;this.name="PageError"}pageUrl},$s=class extends M{constructor(t,o,n){super(t,"TIMEOUT_ERROR",504,n);this.phase=o;this.name="TimeoutError"}phase},Dr=class extends M{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()}},$r=class extends O{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()}},Ar=class extends M{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()}},Er=class extends O{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()}},Mr=class extends M{constructor(t,o,n,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=n;this.failureReason=s;this.summaryAttempt=i;this.name="SummarizationError"}conversationId;messageCount;failureReason;summaryAttempt;isRetryable(){return this.failureReason==="provider_error"||this.failureReason==="insufficient_tokens"}getSuggestedRecovery(){switch(this.failureReason){case"provider_error":return"Retry the summarization request or switch to a different summarizer model";case"invalid_response":return"Review the summarizer prompt or use a different model";case"insufficient_tokens":return"Reduce the number of messages to summarize or increase the summary token budget";case"invalid_quality":return"Adjust summarization parameters or use a more capable model";default:return"Manual intervention required"}}getDetailedReport(){let t=`
24
24
  Summarization Error
25
25
  ===================
26
26
  Conversation ID: ${this.conversationId}
@@ -32,7 +32,7 @@ Recovery Action: ${this.getSuggestedRecovery()}
32
32
  Message: ${this.message}`;return this.summaryAttempt?t+`
33
33
 
34
34
  Partial Summary:
35
- ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}},Ps=class extends O{constructor(t,o,n,s,i){super(t,"CONTEXT_WINDOW_CONFIG_ERROR",400,i);this.configField=o;this.providedValue=n;this.constraint=s;this.name="ContextWindowConfigError"}configField;providedValue;constraint;getDetailedReport(){return`
35
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}},Es=class extends M{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()}},Rs=class extends O{constructor(t,o,n){super(t,"CONVERSATION_NOT_FOUND",404,n);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var $t,Et,Px,jl=g(()=>{"use strict";l();$t={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},Et=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<$t.name;i++)t.push(e.name);for(let i=0;i<$t.displayName;i++)t.push(e.displayName);for(let i=0;i<$t.description;i++)t.push(e.description);for(let i=0;i<$t.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<$t.parameterNames;c++)t.push(i);if(a.description)for(let c=0;c<$t.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=>!Px.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}}},Px=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 ct,Ll=g(()=>{"use strict";l();ct=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 Je(r){let e=r?.length?{...Fe.parameters,properties:{...Fe.parameters.properties,category:{type:"string",description:"Optional: filter by category",enum:r}}}:Fe.parameters;return{name:Fe.name,displayName:Fe.displayName,description:Fe.description,parameters:e,category:Fe.category}}function pt(r){return r===Ke}var Ke,Fe,Fl=g(()=>{"use strict";l();Ke="tool.search",Fe={name:Ke,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
43
+ `.trim()}},Ds=class extends M{constructor(t,o,n){super(t,"CONVERSATION_NOT_FOUND",404,n);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var Dt,At,Dx,ql=g(()=>{"use strict";c();Dt={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},At=class{documents=[];avgDocLength=0;idf=new Map;totalDocs=0;docFrequencies=new Map;k1=1.2;b=.75;index(e){this.documents=[],this.docFrequencies.clear(),this.idf.clear();for(let t of e){let o=this.createDocument(t);this.documents.push(o);let n=new Set(o.tokens);for(let s of n)this.docFrequencies.set(s,(this.docFrequencies.get(s)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let o=t?.limit??5,n=t?.category,s=t?.minScore??0,i=this.tokenize(e.toLowerCase());if(i.length===0)return[];let a=[];for(let l of this.documents){if(n&&l.tool.category!==n)continue;let p=this.computeBM25Score(i,l);p>s&&a.push({toolName:l.toolName,score:p,tool:l.tool})}return a.sort((l,p)=>p.score-l.score).slice(0,o).map(({toolName:l,score:p,tool:d})=>({toolName:l,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<Dt.name;i++)t.push(e.name);for(let i=0;i<Dt.displayName;i++)t.push(e.displayName);for(let i=0;i<Dt.description;i++)t.push(e.description);for(let i=0;i<Dt.category;i++)t.push(e.category);if(e.parameters?.properties)for(let[i,a]of Object.entries(e.parameters.properties)){for(let l=0;l<Dt.parameterNames;l++)t.push(i);if(a.description)for(let l=0;l<Dt.parameterDescriptions;l++)t.push(a.description)}let o=t.join(" ").toLowerCase(),n=this.tokenize(o),s=this.computeTermFrequencies(n);return{toolName:e.name,tool:e,text:o,tokens:n,length:n.length,termFrequencies:s}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!Dx.has(t))}computeTermFrequencies(e){let t=new Map;for(let o of e)t.set(o,(t.get(o)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let o=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,o)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,o)=>t+o.length,0)/this.documents.length}computeBM25Score(e,t){let o=0;for(let n of e){let s=t.termFrequencies.get(n)||0;if(s===0)continue;let i=this.idf.get(n)||0,a=t.length,l=s*(this.k1+1),p=s+this.k1*(1-this.b+this.b*(a/this.avgDocLength));o+=i*(l/p)}return o}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},Dx=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 mt,Wl=g(()=>{"use strict";c();mt=class r{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let o of t)this.discoveredTools.add(o);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new r;for(let o of e)if(o.role==="tool"){let n=o;if(typeof n.content=="string")try{let s=JSON.parse(n.content);if(s.query&&s.tools&&Array.isArray(s.tools)){let i=s.tools.map(a=>typeof a=="string"?a:a.name).filter(Boolean);i.length>0&&t.recordDiscovery(s.query,i)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}}});function Qe(r){let e=r?.length?{...We.parameters,properties:{...We.parameters.properties,category:{type:"string",description:"Optional: filter by category",enum:r}}}:We.parameters;return{name:We.name,displayName:We.displayName,description:We.description,parameters:e,category:We.category}}function dt(r){return r===Ve}var Ve,We,Ul=g(()=>{"use strict";c();Ve="tool.search",We={name:Ve,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 Mr(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=Rx[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 Rx,ql=g(()=>{"use strict";l();Rx={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 vn=g(()=>{"use strict";l();jl();Ll();Fl();ql()});function Gl(r){if(!r)return;let e=r.toLowerCase();if(e in Fs)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function Bl(r){dt.init(r)}function ut(r){return dt.shouldLog(r)}function fe(r){dt.error(r)}function N(r){dt.warn(r)}function S(r){dt.info(r)}function y(r){dt.debug(r)}function Qe(r){dt.trace(r)}function zl(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=zl(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function oe(r,e,t){ut("debug")&&(y(`[${e}][${r}] Messages (${t.length}):`),t.forEach((o,n)=>{y(`[${e}][${r}] #${n} role=${o?.role} content=${A(o?.content,300)}`)}))}function Ws(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(", ")}]`),ut("debug")&&e.forEach(s=>{y(`[AIClient][${r}] tool=${t(s)} description=${A(o(s),200)} schema=${A(JSON.stringify(n(s)),500)}`)})}var Cn,Ve,Fs,qs,dt,_=g(()=>{"use strict";l();Cn=require("fs"),Ve=require("path"),Fs={error:0,warn:1,info:2,debug:3,trace:4},qs=class{_enabled=!1;_level="info";_logFile=(0,Ve.join)(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=Gl(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=Gl(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=(0,Ve.isAbsolute)(this._logFile)?this._logFile:(0,Ve.resolve)(process.cwd(),this._logFile),(0,Cn.mkdirSync)((0,Ve.dirname)(this._logFile),{recursive:!0}),(0,Cn.appendFileSync)(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&&Fs[e]<=Fs[this._level]}getLevel(){return this._level}write(e,t){if(!this.shouldLog(e))return;let o=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${zl(t)}`;(0,Cn.appendFileSync)(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)}},dt=new qs});var Mt={};ee(Mt,{fetchUrlAsBase64:()=>Hs,getMimeType:()=>Us,isDataUri:()=>Gs,normalizeImagePart:()=>Zl,parseDataUri:()=>Bs,parseFileEnvelope:()=>Ye,readFileAsBase64:()=>zs,toDataUri:()=>Yl});function Us(r){let e=Xl.extname(r).toLowerCase();return Dx[e]||"application/octet-stream"}function Gs(r){return r.startsWith("data:")}function Bs(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function Yl(r,e){return`data:${e};base64,${r}`}async function zs(r){try{return{data:(await Ql.readFile(r)).toString("base64"),mimeType:Us(r)}}catch(e){throw new M(`Failed to read image file: ${r}`,e)}}async function Hs(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 Ye(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 Zl(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await zs(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(Gs(e)){let t=Bs(e);if(!t)throw new M(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Hs(e)}throw new M(`Unknown ImagePart type: ${r.type}`)}var Ql,Xl,Dx,Ae=g(()=>{"use strict";l();Ql=x(require("fs/promises"),1),Xl=x(require("path"),1);pe();Dx={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var An,Me,yt=g(()=>{"use strict";l();An=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 An});var gc,Mn,hc,ti=g(()=>{"use strict";l();gc=x(require("fs/promises"),1),Mn=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 gc.rm(n.cloneDir,{recursive:!0,force:!0}),this.totalBytes=Math.max(0,this.totalBytes-n.sizeBytes),this.registry.delete(s)}catch{break}}}},hc=new Mn});async function K(r,e,t,o){return(t??Ax).resolve(r,e,o)}function yc(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=bc.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var bc,Nn,Ax,xe=g(()=>{"use strict";l();bc=x(require("crypto"),1),Nn=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=yc(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=yc(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}},Ax=new Nn});var Tc={};ee(Tc,{ToolRuntimeContext:()=>oi});var oi,wc=g(()=>{"use strict";l();yt();ti();xe();oi=class{processRegistry=new An;cloneState=new Mn;githubTokenStore=new Nn}});var xc,vc,Cc,kc,Sc,_c=g(()=>{"use strict";l();xc="fs.read_file",vc="Read File",Cc="Read the contents of a file at the given path. Returns the file content as a string.",kc="filesystem",Sc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});async function Mx(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(!Ot.existsSync(e))throw new Error(`File not found: ${e}`);if(Ot.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return Ot.readFileSync(e,t)}var Ot,It,ni=g(()=>{"use strict";l();Ot=x(require("fs"),1);_c();_();It={name:xc,displayName:vc,description:Cc,parameters:Sc,category:kc,execute:Mx}});var Pc,Rc,$c,Ec,Dc,Ac=g(()=>{"use strict";l();Pc="fs.write_file",Rc="Write File",$c="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.",Ec="filesystem",Dc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function Nx(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=Mc.dirname(e);return jt.existsSync(n)||jt.mkdirSync(n,{recursive:!0}),jt.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var jt,Mc,Lt,ri=g(()=>{"use strict";l();jt=x(require("fs"),1),Mc=x(require("path"),1);Ac();_();Lt={name:Pc,displayName:Rc,description:$c,parameters:Dc,category:Ec,execute:Nx,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var Nc,Oc,Ic,jc,Lc,Fc=g(()=>{"use strict";l();Nc="fs.append_file",Oc="Append File",Ic="Append content to the end of a file. Creates the file if it does not exist.",jc="filesystem",Lc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function Ox(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=qc.dirname(e);return Ft.existsSync(n)||Ft.mkdirSync(n,{recursive:!0}),Ft.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Ft,qc,qt,si=g(()=>{"use strict";l();Ft=x(require("fs"),1),qc=x(require("path"),1);Fc();qt={name:Nc,displayName:Oc,description:Ic,parameters:Lc,category:jc,execute:Ox,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var Wc,Uc,Gc,Bc,zc,Hc=g(()=>{"use strict";l();Wc="fs.delete_file",Uc="Delete File",Gc="Remove/delete a file from the filesystem. Does not delete directories.",Bc="filesystem",zc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function Ix(r){let e=r.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Wt.existsSync(e))throw new Error(`File not found: ${e}`);if(Wt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Wt.unlinkSync(e),`File deleted successfully: ${e}`}var Wt,Ut,ii=g(()=>{"use strict";l();Wt=x(require("fs"),1);Hc();_();Ut={name:Wc,displayName:Uc,description:Gc,parameters:zc,category:Bc,execute:Ix,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var Kc,Jc,Vc,Qc,Xc,Yc=g(()=>{"use strict";l();Kc="fs.exists",Jc="Exists",Vc="Check if a file or directory exists at the given path. Returns true or false.",Qc="filesystem",Xc={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function jx(r){let e=r.path;if(!e)throw new Error("path is required");let t=Zc.existsSync(e);return JSON.stringify({exists:t,path:e})}var Zc,Gt,ai=g(()=>{"use strict";l();Zc=x(require("fs"),1);Yc();Gt={name:Kc,displayName:Jc,description:Vc,parameters:Xc,category:Qc,execute:jx}});var ep,tp,op,np,rp,sp=g(()=>{"use strict";l();ep="fs.stat",tp="Stat",op="Get file or directory information including size, type, and modification date.",np="filesystem",rp={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function Lx(r){let e=r.path;if(!e)throw new Error("path is required");if(!qr.existsSync(e))throw new Error(`Path not found: ${e}`);let t=qr.statSync(e);return JSON.stringify({path:e,type:t.isDirectory()?"directory":t.isFile()?"file":"other",size:t.size,created:t.birthtime.toISOString(),modified:t.mtime.toISOString(),accessed:t.atime.toISOString(),permissions:t.mode.toString(8)})}var qr,Bt,li=g(()=>{"use strict";l();qr=x(require("fs"),1);sp();Bt={name:ep,displayName:tp,description:op,parameters:rp,category:np,execute:Lx}});var ip,ap,lp,cp,pp,mp=g(()=>{"use strict";l();ip="fs.list_dir",ap="List Directory",lp="List files and directories at the given path. Optionally recurse into subdirectories.",cp="filesystem",pp={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});function up(r,e,t,o=""){let n=bt.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=dp.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&up(i,!0,t,a);else if(s.isFile()){let c=bt.statSync(i);t.push({name:a,type:"file",size:c.size})}}}async function Fx(r){let e=r.path,t=r.recursive===!0;if(!e)throw new Error("path is required");if(!bt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!bt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[];return up(e,t,n),JSON.stringify(n,null,2)}var bt,dp,zt,ci=g(()=>{"use strict";l();bt=x(require("fs"),1),dp=x(require("path"),1);mp();zt={name:ip,displayName:ap,description:lp,parameters:pp,category:cp,execute:Fx}});var fp,gp,hp,yp,bp,Tp=g(()=>{"use strict";l();fp="fs.create_dir",gp="Create Directory",hp="Create a directory at the given path. Creates parent directories recursively if they do not exist.",yp="filesystem",bp={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});async function qx(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(Ht.existsSync(e)){if(Ht.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Ht.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var Ht,Kt,pi=g(()=>{"use strict";l();Ht=x(require("fs"),1);Tp();Kt={name:fp,displayName:gp,description:hp,parameters:bp,category:yp,execute:qx}});var wp,xp,vp,Cp,kp,Sp=g(()=>{"use strict";l();wp="fs.move",xp="Move",vp="Move or rename a file or directory from one path to another.",Cp="filesystem",kp={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});async function Wx(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(!Tt.existsSync(e))throw new Error(`Source not found: ${e}`);let o=_p.dirname(t);return Tt.existsSync(o)||Tt.mkdirSync(o,{recursive:!0}),Tt.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var Tt,_p,Jt,mi=g(()=>{"use strict";l();Tt=x(require("fs"),1),_p=x(require("path"),1);Sp();Jt={name:wp,displayName:xp,description:vp,parameters:kp,category:Cp,execute:Wx,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var Pp,Rp,$p,Ep,Dp,Ap=g(()=>{"use strict";l();Pp="fs.copy",Rp="Copy",$p="Copy a file or directory from one path to another. Recursively copies directories.",Ep="filesystem",Dp={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function Mp(r,e){if(ge.statSync(r).isDirectory()){ge.existsSync(e)||ge.mkdirSync(e,{recursive:!0});let o=ge.readdirSync(r);for(let n of o)Mp(On.join(r,n),On.join(e,n))}else ge.copyFileSync(r,e)}async function Ux(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(!ge.existsSync(e))throw new Error(`Source not found: ${e}`);let o=On.dirname(t);return ge.existsSync(o)||ge.mkdirSync(o,{recursive:!0}),Mp(e,t),`Copied ${ge.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var ge,On,Vt,di=g(()=>{"use strict";l();ge=x(require("fs"),1),On=x(require("path"),1);Ap();Vt={name:Pp,displayName:Rp,description:$p,parameters:Dp,category:Ep,execute:Ux,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var Np,Op,Ip,jp,Lp,Fp=g(()=>{"use strict";l();Np="fs.read_file_range",Op="Read File Range",Ip="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",jp="filesystem",Lp={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});async function Gx(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(!Qt.existsSync(e))throw new Error(`File not found: ${e}`);if(Qt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=Qt.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((f,b)=>`${c+b}: ${f}`).join(`
54
- `);return`Lines ${c}-${p} of ${a} total:
55
- ${m}`}var Qt,Xt,ui=g(()=>{"use strict";l();Qt=x(require("fs"),1);Fp();Xt={name:Np,displayName:Op,description:Ip,parameters:Lp,category:jp,execute:Gx}});var qp,Wp,Up,Gp,Bp,zp=g(()=>{"use strict";l();qp="fs.search",Wp="Search",Up="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Gp="filesystem",Bp={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});function Bx(r,e,t,o){try{let s=tt.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 Kp(r,e,t,o,n){let s=tt.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=Hp.join(r,i.name);i.isDirectory()&&t?Kp(a,e,!0,o,n):i.isFile()&&Bx(a,e,o,n)}}async function zx(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 m=t;s||(m=m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let f=i?"":"i";a=new RegExp(m,f)}if(!tt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!tt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(Kp(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 tt,Hp,Yt,fi=g(()=>{"use strict";l();tt=x(require("fs"),1),Hp=x(require("path"),1);zp();_();Yt={name:qp,displayName:Wp,description:Up,parameters:Bp,category:Gp,execute:zx}});var Jp,Vp,Qp,Xp,Yp,Zp=g(()=>{"use strict";l();Jp="fs.replace_in_file",Vp="Replace In File",Qp="Find and replace text in a file. Returns the number of replacements made.",Xp="filesystem",Yp={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});async function Hx(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(!ot.existsSync(e))throw new Error(`File not found: ${e}`);if(ot.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let s=ot.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 ot.writeFileSync(e,c,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var ot,Zt,gi=g(()=>{"use strict";l();ot=x(require("fs"),1);Zp();Zt={name:Jp,displayName:Vp,description:Qp,parameters:Yp,category:Xp,execute:Hx,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 em,tm,om,nm,rm,sm=g(()=>{"use strict";l();em="fs.tree",tm="Tree",om="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",nm="filesystem",rm={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});function im(r,e,t,o,n){if(t>o)return;let i=eo.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}/`),im(Wr.join(r,c.name),e+m,t+1,o,n)):n.push(`${e}${d}${c.name}`)}}async function Kx(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!eo.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!eo.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${Wr.basename(e)}/`];return im(e,"",1,t,s),s.join(`
58
- `)}var eo,Wr,to,hi=g(()=>{"use strict";l();eo=x(require("fs"),1),Wr=x(require("path"),1);sm();to={name:em,displayName:tm,description:om,parameters:rm,category:nm,execute:Kx}});var am,lm,cm,pm,mm,dm=g(()=>{"use strict";l();am="fs.glob",lm="Glob Pattern Match",cm='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',pm="filesystem",mm={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});async function Jx(r){let e=r.pattern,t=r.cwd,o=r.ignore,n=r.onlyFiles!==!1,s=r.onlyDirectories===!0,i=r.absolute===!0;if(!e)throw new Error("pattern is required");let a=e.replace(/\\/g,"/");try{let c=await(0,um.default)(a,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:n,onlyDirectories:s,absolute:i,dot:!0});return JSON.stringify({pattern:e,files:c,count:c.length},null,2)}catch(c){throw new Error(`Failed to glob pattern "${e}": ${c.message}`)}}var um,oo,yi=g(()=>{"use strict";l();um=x(require("fast-glob"),1);dm();oo={name:am,displayName:lm,description:cm,parameters:mm,category:pm,execute:Jx}});var fm,gm,hm,ym,bm,Tm=g(()=>{"use strict";l();fm="fs.delete_dir",gm="Delete Directory",hm="Delete a directory and all its contents recursively",ym="filesystem",bm={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});async function Vx(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!(0,Ur.existsSync)(e))throw new Error(`Directory does not exist: ${e}`);if(!(0,Ur.statSync)(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await(0,wm.rm)(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var wm,Ur,no,bi=g(()=>{"use strict";l();wm=require("fs/promises"),Ur=require("fs");Tm();no={name:fm,displayName:gm,description:hm,parameters:bm,category:ym,execute:Vx,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var xm,vm,Cm,km,Sm,_m=g(()=>{"use strict";l();xm="fs.batch_read",vm="Batch Read Files",Cm="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",km="filesystem",Sm={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});async function Qx(r){let e=r.paths,t=r.encoding||"utf-8",o=r.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let n=[],s=0,i=0;for(let a of e)try{let c=await(0,Pm.readFile)(a,t);n.push({path:a,content:c,success:!0}),s++}catch(c){let p=c.message;if(n.push({path:a,error:p,success:!1}),i++,!o)throw new Error(`Failed to read file "${a}": ${p}`)}return JSON.stringify({total:e.length,success:s,failed:i,results:n},null,2)}var Pm,ro,Ti=g(()=>{"use strict";l();Pm=require("fs/promises");_m();ro={name:xm,displayName:vm,description:Cm,parameters:Sm,category:km,execute:Qx}});var Rm,$m,Em,Dm,Am,Mm=g(()=>{"use strict";l();Rm="fs.batch_write",$m="Batch Write Files",Em="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",Dm="filesystem",Am={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});async function Xx(r){let e=r.files,t=r.encoding||"utf-8",o=r.atomic!==!1,n=r.createDirs!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("files array is required and must not be empty");for(let a of e)if(!a.path||a.content===void 0)throw new Error("Each file must have path and content properties");let s=[],i=[];try{for(let a of e){let c=(0,Gr.resolve)(a.path);if(o){let p=(0,wi.existsSync)(c),d={path:c,existed:p};p&&(d.originalContent=await(0,qe.readFile)(c,t)),s.push(d)}if(n){let p=(0,Gr.dirname)(c);await(0,qe.mkdir)(p,{recursive:!0})}await(0,qe.writeFile)(c,a.content,t),i.push(c)}return JSON.stringify({success:!0,written:i.length,files:i},null,2)}catch(a){if(o&&s.length>0){for(let c of s)try{c.existed&&c.originalContent!==void 0?await(0,qe.writeFile)(c.path,c.originalContent,t):!c.existed&&(0,wi.existsSync)(c.path)&&await(0,qe.unlink)(c.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var qe,Gr,wi,so,xi=g(()=>{"use strict";l();qe=require("fs/promises"),Gr=require("path"),wi=require("fs");Mm();so={name:Rm,displayName:$m,description:Em,parameters:Am,category:Dm,execute:Xx,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var Nm={};ee(Nm,{fsAppendFileTool:()=>qt,fsBatchReadTool:()=>ro,fsBatchWriteTool:()=>so,fsCopyTool:()=>Vt,fsCreateDirTool:()=>Kt,fsDeleteDirTool:()=>no,fsDeleteFileTool:()=>Ut,fsExistsTool:()=>Gt,fsGlobTool:()=>oo,fsListDirTool:()=>zt,fsMoveTool:()=>Jt,fsReadFileRangeTool:()=>Xt,fsReadFileTool:()=>It,fsReplaceInFileTool:()=>Zt,fsSearchTool:()=>Yt,fsStatTool:()=>Bt,fsToolsProject:()=>vi,fsTreeTool:()=>to,fsWriteFileTool:()=>Lt});var vi,Ci=g(()=>{"use strict";l();ni();ri();si();ii();ai();li();ci();pi();mi();di();ui();fi();gi();hi();yi();bi();Ti();xi();ni();ri();si();ii();ai();li();ci();pi();mi();di();ui();fi();gi();hi();yi();bi();Ti();xi();vi={manifest:{key:"fs",name:"fs-tools",displayName:"File System",version:"1.0.0",description:"File system tools for reading, writing, searching, and managing files and directories.",author:"Sajeer",tools:["fs.read_file","fs.write_file","fs.append_file","fs.delete_file","fs.exists","fs.stat","fs.list_dir","fs.create_dir","fs.move","fs.copy","fs.read_file_range","fs.search","fs.replace_in_file","fs.tree","fs.glob","fs.delete_dir","fs.batch_read","fs.batch_write"],category:"filesystem"},tools:[It,Lt,qt,Ut,Gt,Bt,zt,Kt,Jt,Vt,Xt,Yt,Zt,to,oo,no,ro,so],dependencies:{"fast-glob":"^3.3.2"}}});var Om,Im,jm,Lm,Fm,qm=g(()=>{"use strict";l();Om="exec.run",Im="Run",jm="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Lm="execution",Fm={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});async function Yx(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(0,Wm.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"]})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
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 Ir(r){let e=r.getCategories();if(e.length===0)return"No tools are currently available.";let t=["You have access to tools in the following categories:",""];for(let o of e){let s=r.getByCategory(o).length,i=Ax[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 Ax,Gl=g(()=>{"use strict";c();Ax={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 Sn=g(()=>{"use strict";c();ql();Wl();Ul();Gl()});function Hl(r){if(!r)return;let e=r.toLowerCase();if(e in Us)return e;console.warn(`[Toolpack Warning] Invalid log level "${r}". Falling back to "info".`)}function Kl(r){ft.init(r)}function gt(r){return ft.shouldLog(r)}function ge(r){ft.error(r)}function I(r){ft.warn(r)}function k(r){ft.info(r)}function y(r){ft.debug(r)}function Ye(r){ft.trace(r)}function Jl(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 N(r,e=200){try{let t=typeof r=="string"?r:JSON.stringify(r),o=Jl(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function ne(r,e,t){gt("debug")&&(y(`[${e}][${r}] Messages (${t.length}):`),t.forEach((o,n)=>{y(`[${e}][${r}] #${n} role=${o?.role} content=${N(o?.content,300)}`)}))}function Bs(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??{};k(`[AIClient][${r}] tools=[${e.map(t).join(", ")}]`),gt("debug")&&e.forEach(s=>{y(`[AIClient][${r}] tool=${t(s)} description=${N(o(s),200)} schema=${N(JSON.stringify(n(s)),500)}`)})}var _n,Xe,Us,Gs,ft,P=g(()=>{"use strict";c();_n=require("fs"),Xe=require("path"),Us={error:0,warn:1,info:2,debug:3,trace:4},Gs=class{_enabled=!1;_level="info";_logFile=(0,Xe.join)(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=Hl(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=Hl(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=(0,Xe.isAbsolute)(this._logFile)?this._logFile:(0,Xe.resolve)(process.cwd(),this._logFile),(0,_n.mkdirSync)((0,Xe.dirname)(this._logFile),{recursive:!0}),(0,_n.appendFileSync)(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&&Us[e]<=Us[this._level]}getLevel(){return this._level}write(e,t){if(!this.shouldLog(e))return;let o=`[${new Date().toISOString()}] [${e.toUpperCase()}] ${Jl(t)}`;(0,_n.appendFileSync)(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)}},ft=new Gs});var Ot={};te(Ot,{fetchUrlAsBase64:()=>Vs,getMimeType:()=>zs,isDataUri:()=>Hs,normalizeImagePart:()=>oc,parseDataUri:()=>Ks,parseFileEnvelope:()=>et,readFileAsBase64:()=>Js,toDataUri:()=>tc});function zs(r){let e=ec.extname(r).toLowerCase();return Ox[e]||"application/octet-stream"}function Hs(r){return r.startsWith("data:")}function Ks(r){let e=r.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function tc(r,e){return`data:${e};base64,${r}`}async function Js(r){try{return{data:(await Zl.readFile(r)).toString("base64"),mimeType:zs(r)}}catch(e){throw new O(`Failed to read image file: ${r}`,e)}}async function Vs(r){try{let e=await fetch(r);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let t=await e.arrayBuffer(),o=Buffer.from(t),n=e.headers.get("content-type")||"application/octet-stream";return n=n.split(";")[0].trim(),{data:o.toString("base64"),mimeType:n}}catch(e){throw new F(`Failed to download image from URL: ${r}`,"FETCH_ERROR",500,e)}}function et(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 oc(r){if(r.type==="image_data")return{data:r.image_data.data,mimeType:r.image_data.mimeType};if(r.type==="image_file")return await Js(r.image_file.path);if(r.type==="image_url"){let e=r.image_url.url;if(Hs(e)){let t=Ks(e);if(!t)throw new O(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await Vs(e)}throw new O(`Unknown ImagePart type: ${r.type}`)}var Zl,ec,Ox,Me=g(()=>{"use strict";c();Zl=x(require("fs/promises"),1),ec=x(require("path"),1);le();Ox={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var On,Ne,Tt=g(()=>{"use strict";c();On=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)}},Ne=new On});var bc,In,Tc,ri=g(()=>{"use strict";c();bc=x(require("fs/promises"),1),In=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 bc.rm(n.cloneDir,{recursive:!0,force:!0}),this.totalBytes=Math.max(0,this.totalBytes-n.sizeBytes),this.registry.delete(s)}catch{break}}}},Tc=new In});async function V(r,e,t,o){return(t??Ix).resolve(r,e,o)}function wc(r,e){let t=Math.floor(Date.now()/1e3),o={alg:"RS256",typ:"JWT"},n={iat:t-30,exp:t+540,iss:r},s=l=>Buffer.from(JSON.stringify(l)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),i=`${s(o)}.${s(n)}`,a=xc.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var xc,Ln,Ix,ve=g(()=>{"use strict";c();xc=x(require("crypto"),1),Ln=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=wc(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 l=await i.text();throw new Error(`Failed to look up installation for ${o} (${i.status}): ${l}`)}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=wc(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 l=await i.text();throw new Error(`Failed to mint installation token (${i.status}): ${l}`)}let a=await i.json();return this.tokenCache.set(o,{token:a.token,expiresAt:new Date(a.expires_at).getTime()}),a.token}},Ix=new Ln});var vc={};te(vc,{ToolRuntimeContext:()=>si});var si,Cc=g(()=>{"use strict";c();Tt();ri();ve();si=class{processRegistry=new On;cloneState=new In;githubTokenStore=new Ln}});var kc,Sc,_c,Pc,Rc,$c=g(()=>{"use strict";c();kc="fs.read_file",Sc="Read File",_c="Read the contents of a file at the given path. Returns the file content as a string.",Pc="filesystem",Rc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});async function Lx(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(!Lt.existsSync(e))throw new Error(`File not found: ${e}`);if(Lt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return Lt.readFileSync(e,t)}var Lt,jt,ii=g(()=>{"use strict";c();Lt=x(require("fs"),1);$c();P();jt={name:kc,displayName:Sc,description:_c,parameters:Rc,category:Pc,execute:Lx}});var Ec,Dc,Ac,Mc,Nc,Oc=g(()=>{"use strict";c();Ec="fs.write_file",Dc="Write File",Ac="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.",Mc="filesystem",Nc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function jx(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=Ic.dirname(e);return Ft.existsSync(n)||Ft.mkdirSync(n,{recursive:!0}),Ft.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var Ft,Ic,qt,ai=g(()=>{"use strict";c();Ft=x(require("fs"),1),Ic=x(require("path"),1);Oc();P();qt={name:Ec,displayName:Dc,description:Ac,parameters:Nc,category:Mc,execute:jx,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var Lc,jc,Fc,qc,Wc,Uc=g(()=>{"use strict";c();Lc="fs.append_file",jc="Append File",Fc="Append content to the end of a file. Creates the file if it does not exist.",qc="filesystem",Wc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});async function Fx(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=Gc.dirname(e);return Wt.existsSync(n)||Wt.mkdirSync(n,{recursive:!0}),Wt.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Wt,Gc,Ut,li=g(()=>{"use strict";c();Wt=x(require("fs"),1),Gc=x(require("path"),1);Uc();Ut={name:Lc,displayName:jc,description:Fc,parameters:Wc,category:qc,execute:Fx,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var Bc,zc,Hc,Kc,Jc,Vc=g(()=>{"use strict";c();Bc="fs.delete_file",zc="Delete File",Hc="Remove/delete a file from the filesystem. Does not delete directories.",Kc="filesystem",Jc={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});async function qx(r){let e=r.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Gt.existsSync(e))throw new Error(`File not found: ${e}`);if(Gt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Gt.unlinkSync(e),`File deleted successfully: ${e}`}var Gt,Bt,ci=g(()=>{"use strict";c();Gt=x(require("fs"),1);Vc();P();Bt={name:Bc,displayName:zc,description:Hc,parameters:Jc,category:Kc,execute:qx,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var Qc,Xc,Yc,Zc,ep,tp=g(()=>{"use strict";c();Qc="fs.exists",Xc="Exists",Yc="Check if a file or directory exists at the given path. Returns true or false.",Zc="filesystem",ep={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});async function Wx(r){let e=r.path;if(!e)throw new Error("path is required");let t=op.existsSync(e);return JSON.stringify({exists:t,path:e})}var op,zt,pi=g(()=>{"use strict";c();op=x(require("fs"),1);tp();zt={name:Qc,displayName:Xc,description:Yc,parameters:ep,category:Zc,execute:Wx}});var np,rp,sp,ip,ap,lp=g(()=>{"use strict";c();np="fs.stat",rp="Stat",sp="Get file or directory information including size, type, and modification date.",ip="filesystem",ap={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});async function Ux(r){let e=r.path;if(!e)throw new Error("path is required");if(!Gr.existsSync(e))throw new Error(`Path not found: ${e}`);let t=Gr.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 Gr,Ht,mi=g(()=>{"use strict";c();Gr=x(require("fs"),1);lp();Ht={name:np,displayName:rp,description:sp,parameters:ap,category:ip,execute:Ux}});var cp,pp,mp,dp,up,fp=g(()=>{"use strict";c();cp="fs.list_dir",pp="List Directory",mp="List files and directories at the given path. Optionally recurse into subdirectories.",dp="filesystem",up={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});function hp(r,e,t,o=""){let n=wt.readdirSync(r,{withFileTypes:!0});for(let s of n){let i=gp.join(r,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&hp(i,!0,t,a);else if(s.isFile()){let l=wt.statSync(i);t.push({name:a,type:"file",size:l.size})}}}async function Gx(r){let e=r.path,t=r.recursive===!0;if(!e)throw new Error("path is required");if(!wt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!wt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let n=[];return hp(e,t,n),JSON.stringify(n,null,2)}var wt,gp,Kt,di=g(()=>{"use strict";c();wt=x(require("fs"),1),gp=x(require("path"),1);fp();Kt={name:cp,displayName:pp,description:mp,parameters:up,category:dp,execute:Gx}});var yp,bp,Tp,wp,xp,vp=g(()=>{"use strict";c();yp="fs.create_dir",bp="Create Directory",Tp="Create a directory at the given path. Creates parent directories recursively if they do not exist.",wp="filesystem",xp={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});async function Bx(r){let e=r.path,t=r.recursive!==!1;if(!e)throw new Error("path is required");if(Jt.existsSync(e)){if(Jt.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return Jt.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var Jt,Vt,ui=g(()=>{"use strict";c();Jt=x(require("fs"),1);vp();Vt={name:yp,displayName:bp,description:Tp,parameters:xp,category:wp,execute:Bx}});var Cp,kp,Sp,_p,Pp,Rp=g(()=>{"use strict";c();Cp="fs.move",kp="Move",Sp="Move or rename a file or directory from one path to another.",_p="filesystem",Pp={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});async function zx(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(!xt.existsSync(e))throw new Error(`Source not found: ${e}`);let o=$p.dirname(t);return xt.existsSync(o)||xt.mkdirSync(o,{recursive:!0}),xt.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var xt,$p,Qt,fi=g(()=>{"use strict";c();xt=x(require("fs"),1),$p=x(require("path"),1);Rp();Qt={name:Cp,displayName:kp,description:Sp,parameters:Pp,category:_p,execute:zx,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var Ep,Dp,Ap,Mp,Np,Op=g(()=>{"use strict";c();Ep="fs.copy",Dp="Copy",Ap="Copy a file or directory from one path to another. Recursively copies directories.",Mp="filesystem",Np={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});function Ip(r,e){if(he.statSync(r).isDirectory()){he.existsSync(e)||he.mkdirSync(e,{recursive:!0});let o=he.readdirSync(r);for(let n of o)Ip(jn.join(r,n),jn.join(e,n))}else he.copyFileSync(r,e)}async function Hx(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(!he.existsSync(e))throw new Error(`Source not found: ${e}`);let o=jn.dirname(t);return he.existsSync(o)||he.mkdirSync(o,{recursive:!0}),Ip(e,t),`Copied ${he.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var he,jn,Xt,gi=g(()=>{"use strict";c();he=x(require("fs"),1),jn=x(require("path"),1);Op();Xt={name:Ep,displayName:Dp,description:Ap,parameters:Np,category:Mp,execute:Hx,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var Lp,jp,Fp,qp,Wp,Up=g(()=>{"use strict";c();Lp="fs.read_file_range",jp="Read File Range",Fp="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",qp="filesystem",Wp={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});async function Kx(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(!Yt.existsSync(e))throw new Error(`File not found: ${e}`);if(Yt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let i=Yt.readFileSync(e,"utf-8").split(`
53
+ `),a=i.length,l=Math.min(t,a),p=Math.min(o,a),m=i.slice(l-1,p).map((u,b)=>`${l+b}: ${u}`).join(`
54
+ `);return`Lines ${l}-${p} of ${a} total:
55
+ ${m}`}var Yt,Zt,hi=g(()=>{"use strict";c();Yt=x(require("fs"),1);Up();Zt={name:Lp,displayName:jp,description:Fp,parameters:Wp,category:qp,execute:Kx}});var Gp,Bp,zp,Hp,Kp,Jp=g(()=>{"use strict";c();Gp="fs.search",Bp="Search",zp="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Hp="filesystem",Kp={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});function Jx(r,e,t,o){try{let s=nt.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 Qp(r,e,t,o,n){let s=nt.readdirSync(r,{withFileTypes:!0});for(let i of s){if(o.length>=n)break;let a=Vp.join(r,i.name);i.isDirectory()&&t?Qp(a,e,!0,o,n):i.isFile()&&Jx(a,e,o,n)}}async function Vx(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 m=t;s||(m=m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let u=i?"":"i";a=new RegExp(m,u)}if(!nt.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!nt.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(Qp(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 nt,Vp,eo,yi=g(()=>{"use strict";c();nt=x(require("fs"),1),Vp=x(require("path"),1);Jp();P();eo={name:Gp,displayName:Bp,description:zp,parameters:Kp,category:Hp,execute:Vx}});var Xp,Yp,Zp,em,tm,om=g(()=>{"use strict";c();Xp="fs.replace_in_file",Yp="Replace In File",Zp="Find and replace text in a file. Returns the number of replacements made.",em="filesystem",tm={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});async function Qx(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(!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 s=rt.readFileSync(e,"utf-8"),i=0,a=0;for(;(a=s.indexOf(t,a))!==-1;)i++,a+=t.length;if(i===0)return`No occurrences of "${t}" found in ${e}`;let l=s.split(t).join(o);return rt.writeFileSync(e,l,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var rt,to,bi=g(()=>{"use strict";c();rt=x(require("fs"),1);om();to={name:Xp,displayName:Yp,description:Zp,parameters:tm,category:em,execute:Qx,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 nm,rm,sm,im,am,lm=g(()=>{"use strict";c();nm="fs.tree",rm="Tree",sm="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",im="filesystem",am={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});function cm(r,e,t,o,n){if(t>o)return;let i=oo.readdirSync(r,{withFileTypes:!0}).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name));for(let a=0;a<i.length;a++){let l=i[a],p=a===i.length-1,d=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",m=p?" ":"\u2502 ";l.isDirectory()?(n.push(`${e}${d}${l.name}/`),cm(Br.join(r,l.name),e+m,t+1,o,n)):n.push(`${e}${d}${l.name}`)}}async function Xx(r){let e=r.path,t=r.depth||3;if(!e)throw new Error("path is required");if(!oo.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!oo.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${Br.basename(e)}/`];return cm(e,"",1,t,s),s.join(`
58
+ `)}var oo,Br,no,Ti=g(()=>{"use strict";c();oo=x(require("fs"),1),Br=x(require("path"),1);lm();no={name:nm,displayName:rm,description:sm,parameters:am,category:im,execute:Xx}});var pm,mm,dm,um,fm,gm=g(()=>{"use strict";c();pm="fs.glob",mm="Glob Pattern Match",dm='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',um="filesystem",fm={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});async function Yx(r){let e=r.pattern,t=r.cwd,o=r.ignore,n=r.onlyFiles!==!1,s=r.onlyDirectories===!0,i=r.absolute===!0;if(!e)throw new Error("pattern is required");let a=e.replace(/\\/g,"/");try{let l=await(0,hm.default)(a,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:n,onlyDirectories:s,absolute:i,dot:!0});return JSON.stringify({pattern:e,files:l,count:l.length},null,2)}catch(l){throw new Error(`Failed to glob pattern "${e}": ${l.message}`)}}var hm,ro,wi=g(()=>{"use strict";c();hm=x(require("fast-glob"),1);gm();ro={name:pm,displayName:mm,description:dm,parameters:fm,category:um,execute:Yx}});var ym,bm,Tm,wm,xm,vm=g(()=>{"use strict";c();ym="fs.delete_dir",bm="Delete Directory",Tm="Delete a directory and all its contents recursively",wm="filesystem",xm={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});async function Zx(r){let e=r.path,t=r.force!==!1;if(!e)throw new Error("path is required");if(!(0,zr.existsSync)(e))throw new Error(`Directory does not exist: ${e}`);if(!(0,zr.statSync)(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await(0,Cm.rm)(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(n){throw new Error(`Failed to delete directory "${e}": ${n.message}`)}}var Cm,zr,so,xi=g(()=>{"use strict";c();Cm=require("fs/promises"),zr=require("fs");vm();so={name:ym,displayName:bm,description:Tm,parameters:xm,category:wm,execute:Zx,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var km,Sm,_m,Pm,Rm,$m=g(()=>{"use strict";c();km="fs.batch_read",Sm="Batch Read Files",_m="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",Pm="filesystem",Rm={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});async function ev(r){let e=r.paths,t=r.encoding||"utf-8",o=r.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let n=[],s=0,i=0;for(let a of e)try{let l=await(0,Em.readFile)(a,t);n.push({path:a,content:l,success:!0}),s++}catch(l){let p=l.message;if(n.push({path:a,error:p,success:!1}),i++,!o)throw new Error(`Failed to read file "${a}": ${p}`)}return JSON.stringify({total:e.length,success:s,failed:i,results:n},null,2)}var Em,io,vi=g(()=>{"use strict";c();Em=require("fs/promises");$m();io={name:km,displayName:Sm,description:_m,parameters:Rm,category:Pm,execute:ev}});var Dm,Am,Mm,Nm,Om,Im=g(()=>{"use strict";c();Dm="fs.batch_write",Am="Batch Write Files",Mm="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",Nm="filesystem",Om={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});async function tv(r){let e=r.files,t=r.encoding||"utf-8",o=r.atomic!==!1,n=r.createDirs!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("files array is required and must not be empty");for(let a of e)if(!a.path||a.content===void 0)throw new Error("Each file must have path and content properties");let s=[],i=[];try{for(let a of e){let l=(0,Hr.resolve)(a.path);if(o){let p=(0,Ci.existsSync)(l),d={path:l,existed:p};p&&(d.originalContent=await(0,Ue.readFile)(l,t)),s.push(d)}if(n){let p=(0,Hr.dirname)(l);await(0,Ue.mkdir)(p,{recursive:!0})}await(0,Ue.writeFile)(l,a.content,t),i.push(l)}return JSON.stringify({success:!0,written:i.length,files:i},null,2)}catch(a){if(o&&s.length>0){for(let l of s)try{l.existed&&l.originalContent!==void 0?await(0,Ue.writeFile)(l.path,l.originalContent,t):!l.existed&&(0,Ci.existsSync)(l.path)&&await(0,Ue.unlink)(l.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var Ue,Hr,Ci,ao,ki=g(()=>{"use strict";c();Ue=require("fs/promises"),Hr=require("path"),Ci=require("fs");Im();ao={name:Dm,displayName:Am,description:Mm,parameters:Om,category:Nm,execute:tv,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var Lm={};te(Lm,{fsAppendFileTool:()=>Ut,fsBatchReadTool:()=>io,fsBatchWriteTool:()=>ao,fsCopyTool:()=>Xt,fsCreateDirTool:()=>Vt,fsDeleteDirTool:()=>so,fsDeleteFileTool:()=>Bt,fsExistsTool:()=>zt,fsGlobTool:()=>ro,fsListDirTool:()=>Kt,fsMoveTool:()=>Qt,fsReadFileRangeTool:()=>Zt,fsReadFileTool:()=>jt,fsReplaceInFileTool:()=>to,fsSearchTool:()=>eo,fsStatTool:()=>Ht,fsToolsProject:()=>Si,fsTreeTool:()=>no,fsWriteFileTool:()=>qt});var Si,_i=g(()=>{"use strict";c();ii();ai();li();ci();pi();mi();di();ui();fi();gi();hi();yi();bi();Ti();wi();xi();vi();ki();ii();ai();li();ci();pi();mi();di();ui();fi();gi();hi();yi();bi();Ti();wi();xi();vi();ki();Si={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:[jt,qt,Ut,Bt,zt,Ht,Kt,Vt,Qt,Xt,Zt,eo,to,no,ro,so,io,ao],dependencies:{"fast-glob":"^3.3.2"}}});var jm,Fm,qm,Wm,Um,Gm=g(()=>{"use strict";c();jm="exec.run",Fm="Run",qm="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",Wm="execution",Um={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});async function ov(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(0,Bm.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"]})||"(command completed with no output)"}catch(n){let s=n.stdout||"",i=n.stderr||"";return`Command failed (exit code ${n.status??"unknown"}):
59
59
  STDOUT:
60
60
  ${s}
61
61
  STDERR:
62
- ${i}`}}var Wm,io,ki=g(()=>{"use strict";l();Wm=require("child_process");qm();_();io={name:Om,displayName:Im,description:jm,parameters:Fm,category:Lm,execute:Yx,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var Um,Gm,Bm,zm,Hm,Km=g(()=>{"use strict";l();Um="exec.run_shell",Gm="Run Shell",Bm="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",zm="execution",Hm={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});function Zx(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function ev(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(0,Jm.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Zx()})||"(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 Bm,lo,Pi=g(()=>{"use strict";c();Bm=require("child_process");Gm();P();lo={name:jm,displayName:Fm,description:qm,parameters:Um,category:Wm,execute:ov,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var zm,Hm,Km,Jm,Vm,Qm=g(()=>{"use strict";c();zm="exec.run_shell",Hm="Run Shell",Km="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",Jm="execution",Vm={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});function nv(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function rv(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(0,Xm.execSync)(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:nv()})||"(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 Jm,ao,Si=g(()=>{"use strict";l();Jm=require("child_process");Km();_();ao={name:Um,displayName:Gm,description:Bm,parameters:Hm,category:zm,execute:ev,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});var Vm,Qm,Xm,Ym,Zm,ed=g(()=>{"use strict";l();Vm="exec.run_background",Qm="Run Background",Xm="Start a command as a background process. Returns a process ID that can be used with exec.read_output, exec.kill, and exec.list_processes.",Ym="execution",Zm={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});async function tv(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=(0,td.spawn)(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 td,lo,_i=g(()=>{"use strict";l();td=require("child_process");yt();ed();_();lo={name:Vm,displayName:Qm,description:Xm,parameters:Zm,category:Ym,execute:tv,confirmation:{level:"medium",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var od,nd,rd,sd,id,ad=g(()=>{"use strict";l();od="exec.run_blocking",nd="Run Blocking",rd="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.",sd="execution",id={type:"object",properties:{command:{type:"string",description:"The shell command to execute. Supports pipes, redirects, and shell features."},cwd:{type:"string",description:"Working directory for the command (optional). Defaults to the current working directory."}},required:["command"]}});function ov(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function nv(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=(0,ld.spawn)(e,[],{cwd:t,shell:ov(),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 ld,co,Pi=g(()=>{"use strict";l();ld=require("child_process");ad();_();co={name:od,displayName:nd,description:rd,parameters:id,category:sd,execute:nv,confirmation:{level:"medium",reason:"This will execute a shell command and block until it completes.",showArgs:["command"]}}});var cd,pd,md,dd,ud,fd=g(()=>{"use strict";l();cd="exec.read_output",pd="Read Output",md="Read stdout and stderr from a background process started with exec.run_background.",dd="execution",ud={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function rv(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 po,Ri=g(()=>{"use strict";l();yt();fd();po={name:cd,displayName:pd,description:md,parameters:ud,category:dd,execute:rv}});var gd,hd,yd,bd,Td,wd=g(()=>{"use strict";l();gd="exec.tail_output",hd="Tail Process Output",yd="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.",bd="execution",Td={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 sv(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
- `),p=c.slice(-o).join(`
66
+ ${i}`}}var Xm,co,Ri=g(()=>{"use strict";c();Xm=require("child_process");Qm();P();co={name:zm,displayName:Hm,description:Km,parameters:Vm,category:Jm,execute:rv,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});var Ym,Zm,ed,td,od,nd=g(()=>{"use strict";c();Ym="exec.run_background",Zm="Run Background",ed="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.",td="execution",od={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});async function sv(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=(0,rd.spawn)(t,[],{cwd:o,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),i=(e?.processRegistry??Ne).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 rd,po,$i=g(()=>{"use strict";c();rd=require("child_process");Tt();nd();P();po={name:Ym,displayName:Zm,description:ed,parameters:od,category:td,execute:sv,confirmation:{level:"medium",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var sd,id,ad,ld,cd,pd=g(()=>{"use strict";c();sd="exec.run_blocking",id="Run Blocking",ad="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.",ld="execution",cd={type:"object",properties:{command:{type:"string",description:"The shell command to execute. Supports pipes, redirects, and shell features."},cwd:{type:"string",description:"Working directory for the command (optional). Defaults to the current working directory."}},required:["command"]}});function iv(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function av(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=(0,md.spawn)(e,[],{cwd:t,shell:iv(),stdio:["ignore","pipe","pipe"]});i.stdout?.on("data",a=>{n+=a.toString(),n.length>2e6&&(n=n.slice(-1e6))}),i.stderr?.on("data",a=>{s+=a.toString(),s.length>2e6&&(s=s.slice(-1e6))}),i.on("close",a=>{let l=a??0;y(`[exec.run-blocking] finished exitCode=${l} stdout_len=${n.length} stderr_len=${s.length}`),o(JSON.stringify({exitCode:l,stdout:n||"(no output)",stderr:s||"",success:l===0}))}),i.on("error",a=>{y(`[exec.run-blocking] spawn error: ${a.message}`),o(JSON.stringify({exitCode:1,stdout:"",stderr:a.message,success:!1}))})})}var md,mo,Ei=g(()=>{"use strict";c();md=require("child_process");pd();P();mo={name:sd,displayName:id,description:ad,parameters:cd,category:ld,execute:av,confirmation:{level:"medium",reason:"This will execute a shell command and block until it completes.",showArgs:["command"]}}});var dd,ud,fd,gd,hd,yd=g(()=>{"use strict";c();dd="exec.read_output",ud="Read Output",fd="Read stdout and stderr from a background process started with exec.run_background.",gd="execution",hd={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function lv(r,e){let t=r.process_id;if(!t)throw new Error("process_id is required");let n=(e?.processRegistry??Ne).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 uo,Di=g(()=>{"use strict";c();Tt();yd();uo={name:dd,displayName:ud,description:fd,parameters:hd,category:gd,execute:lv}});var bd,Td,wd,xd,vd,Cd=g(()=>{"use strict";c();bd="exec.tail_output",Td="Tail Process Output",wd="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.",xd="execution",vd={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 cv(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??Ne).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,l=s.stdout.split(`
67
+ `),p=l.slice(-o).join(`
68
68
  `).trim(),m=s.stderr.split(`
69
- `).filter(f=>f.trim()).slice(-3).join(`
70
- `).trim();return JSON.stringify({id:t,alive:i,exitCode:a,lastLines:p||"(no output yet)",lastStderr:m||"",totalStdoutLines:c.length})}var mo,$i=g(()=>{"use strict";l();yt();wd();mo={name:gd,displayName:hd,description:yd,parameters:Td,category:bd,execute:sv}});var xd,vd,Cd,kd,Sd,_d=g(()=>{"use strict";l();xd="exec.kill",vd="Kill",Cd="Kill a background process started with exec.run_background.",kd="execution",Sd={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function iv(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 uo,Ei=g(()=>{"use strict";l();yt();_d();uo={name:xd,displayName:vd,description:Cd,parameters:Sd,category:kd,execute:iv,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var Pd,Rd,$d,Ed,Dd,Ad=g(()=>{"use strict";l();Pd="exec.list_processes",Rd="List Processes",$d="List all managed background processes started with exec.run_background, including their status.",Ed="execution",Dd={type:"object",properties:{}}});async function av(r,e){let o=(e?.processRegistry??Me).list();return o.length===0?"No managed background processes.":JSON.stringify(o,null,2)}var fo,Di=g(()=>{"use strict";l();yt();Ad();fo={name:Pd,displayName:Rd,description:$d,parameters:Dd,category:Ed,execute:av}});var Md={};ee(Md,{execKillTool:()=>uo,execListProcessesTool:()=>fo,execReadOutputTool:()=>po,execRunBackgroundTool:()=>lo,execRunBlockingTool:()=>co,execRunShellTool:()=>ao,execRunTool:()=>io,execTailOutputTool:()=>mo,execToolsProject:()=>Ai});var Ai,Mi=g(()=>{"use strict";l();ki();Si();_i();Pi();Ri();$i();Ei();Di();ki();Si();_i();Pi();Ri();$i();Ei();Di();Ai={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:[io,ao,lo,co,po,mo,uo,fo],dependencies:{}}});var Nd,Od,Id,jd,Ld,Fd=g(()=>{"use strict";l();Nd="system.info",Od="Info",Id="Get system information including OS, CPU, memory, and architecture.",jd="system",Ld={type:"object",properties:{}}});async function lv(r){return y("[system.info] execute"),JSON.stringify({platform:q.platform(),arch:q.arch(),release:q.release(),hostname:q.hostname(),uptime:q.uptime(),cpus:{model:q.cpus()[0]?.model||"unknown",count:q.cpus().length},memory:{total:q.totalmem(),free:q.freemem(),used:q.totalmem()-q.freemem()},homedir:q.homedir(),tmpdir:q.tmpdir(),nodeVersion:process.version},null,2)}var q,go,Ni=g(()=>{"use strict";l();q=x(require("os"),1);Fd();_();go={name:Nd,displayName:Od,description:Id,parameters:Ld,category:jd,execute:lv}});var qd,Wd,Ud,Gd,Bd,zd=g(()=>{"use strict";l();qd="system.env",Wd="Environment",Ud="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",Gd="system",Bd={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function cv(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 ho,Oi=g(()=>{"use strict";l();zd();_();ho={name:qd,displayName:Wd,description:Ud,parameters:Bd,category:Gd,execute:cv}});var Hd,Kd,Jd,Vd,Qd,Xd=g(()=>{"use strict";l();Hd="system.set_env",Kd="Set Environment",Jd="Set an environment variable for the current session. Does not persist across restarts.",Vd="system",Qd={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function pv(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 yo,Ii=g(()=>{"use strict";l();Xd();yo={name:Hd,displayName:Kd,description:Jd,parameters:Qd,category:Vd,execute:pv,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var Yd,Zd,eu,tu,ou,nu=g(()=>{"use strict";l();Yd="system.cwd",Zd="Current Directory",eu="Get the current working directory of the process.",tu="system",ou={type:"object",properties:{}}});async function mv(r){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var bo,ji=g(()=>{"use strict";l();nu();_();bo={name:Yd,displayName:Zd,description:eu,parameters:ou,category:tu,execute:mv}});var ru,su,iu,au,lu,cu=g(()=>{"use strict";l();ru="system.disk_usage",su="Disk Usage",iu="Get disk usage information for a given path or the root filesystem.",au="system",lu={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});function Li(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 dv(r){let t=r.path||(process.platform==="win32"?mu.tmpdir():"/");t=Br.resolve(t);let o=process.platform==="win32";try{let n=pu.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:Li(Number(s)),used:Li(Number(c)),available:Li(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(n){try{if(o){let c=Br.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=(0,Fi.execSync)(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),m=JSON.parse(d.trim()),f=m.Total||0,b=m.Free||0,h=m.Used||0,T=f>0?Math.round(h/f*100):0;return JSON.stringify({path:t,filesystem:m.Name||"NTFS",size:`${(f/1024**3).toFixed(1)}G`,used:`${(h/1024**3).toFixed(1)}G`,available:`${(b/1024**3).toFixed(1)}G`,usePercent:`${T}%`,mountedOn:m.Drive||`${c}`},null,2)}let s=(0,Fi.execSync)(`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 pu,mu,Br,Fi,To,qi=g(()=>{"use strict";l();pu=x(require("fs"),1),mu=x(require("os"),1),Br=x(require("path"),1),Fi=require("child_process");cu();To={name:ru,displayName:su,description:iu,parameters:lu,category:au,execute:dv}});var du={};ee(du,{systemCwdTool:()=>bo,systemDiskUsageTool:()=>To,systemEnvTool:()=>ho,systemInfoTool:()=>go,systemSetEnvTool:()=>yo,systemToolsProject:()=>Wi});var Wi,Ui=g(()=>{"use strict";l();Ni();Oi();Ii();ji();qi();Ni();Oi();Ii();ji();qi();Wi={manifest:{key:"system",name:"system-tools",displayName:"System",version:"1.0.0",description:"System tools for querying OS info, environment variables, working directory, and disk usage.",author:"Sajeer",tools:["system.info","system.env","system.set_env","system.cwd","system.disk_usage"],category:"system"},tools:[go,ho,yo,bo,To],dependencies:{}}});var uu,fu,gu,hu,yu,bu=g(()=>{"use strict";l();uu="http.get",fu="GET",gu="Make an HTTP GET request to a URL and return the response body.",hu="http",yu={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 uv(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>Tu?`${s}
72
- ${n.substring(0,Tu)}
69
+ `).filter(u=>u.trim()).slice(-3).join(`
70
+ `).trim();return JSON.stringify({id:t,alive:i,exitCode:a,lastLines:p||"(no output yet)",lastStderr:m||"",totalStdoutLines:l.length})}var fo,Ai=g(()=>{"use strict";c();Tt();Cd();fo={name:bd,displayName:Td,description:wd,parameters:vd,category:xd,execute:cv}});var kd,Sd,_d,Pd,Rd,$d=g(()=>{"use strict";c();kd="exec.kill",Sd="Kill",_d="Kill a background process started with exec.run_background.",Pd="execution",Rd={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function pv(r,e){let t=r.process_id;if(!t)throw new Error("process_id is required");let o=e?.processRegistry??Ne,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 go,Mi=g(()=>{"use strict";c();Tt();$d();go={name:kd,displayName:Sd,description:_d,parameters:Rd,category:Pd,execute:pv,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var Ed,Dd,Ad,Md,Nd,Od=g(()=>{"use strict";c();Ed="exec.list_processes",Dd="List Processes",Ad="List all managed background processes started with exec.run_background, including their status.",Md="execution",Nd={type:"object",properties:{}}});async function mv(r,e){let o=(e?.processRegistry??Ne).list();return o.length===0?"No managed background processes.":JSON.stringify(o,null,2)}var ho,Ni=g(()=>{"use strict";c();Tt();Od();ho={name:Ed,displayName:Dd,description:Ad,parameters:Nd,category:Md,execute:mv}});var Id={};te(Id,{execKillTool:()=>go,execListProcessesTool:()=>ho,execReadOutputTool:()=>uo,execRunBackgroundTool:()=>po,execRunBlockingTool:()=>mo,execRunShellTool:()=>co,execRunTool:()=>lo,execTailOutputTool:()=>fo,execToolsProject:()=>Oi});var Oi,Ii=g(()=>{"use strict";c();Pi();Ri();$i();Ei();Di();Ai();Mi();Ni();Pi();Ri();$i();Ei();Di();Ai();Mi();Ni();Oi={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:[lo,co,po,mo,uo,fo,go,ho],dependencies:{}}});var Ld,jd,Fd,qd,Wd,Ud=g(()=>{"use strict";c();Ld="system.info",jd="Info",Fd="Get system information including OS, CPU, memory, and architecture.",qd="system",Wd={type:"object",properties:{}}});async function dv(r){return y("[system.info] execute"),JSON.stringify({platform:W.platform(),arch:W.arch(),release:W.release(),hostname:W.hostname(),uptime:W.uptime(),cpus:{model:W.cpus()[0]?.model||"unknown",count:W.cpus().length},memory:{total:W.totalmem(),free:W.freemem(),used:W.totalmem()-W.freemem()},homedir:W.homedir(),tmpdir:W.tmpdir(),nodeVersion:process.version},null,2)}var W,yo,Li=g(()=>{"use strict";c();W=x(require("os"),1);Ud();P();yo={name:Ld,displayName:jd,description:Fd,parameters:Wd,category:qd,execute:dv}});var Gd,Bd,zd,Hd,Kd,Jd=g(()=>{"use strict";c();Gd="system.env",Bd="Environment",zd="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",Hd="system",Kd={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function uv(r){let e=r.key;if(y(`[system.env] execute key=${e??"all"}`),e){let n=process.env[e];return n===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:n})}let t={},o=Object.keys(process.env).sort();for(let n of o)process.env[n]!==void 0&&(t[n]=process.env[n]);return JSON.stringify(t,null,2)}var bo,ji=g(()=>{"use strict";c();Jd();P();bo={name:Gd,displayName:Bd,description:zd,parameters:Kd,category:Hd,execute:uv}});var Vd,Qd,Xd,Yd,Zd,eu=g(()=>{"use strict";c();Vd="system.set_env",Qd="Set Environment",Xd="Set an environment variable for the current session. Does not persist across restarts.",Yd="system",Zd={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function fv(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 To,Fi=g(()=>{"use strict";c();eu();To={name:Vd,displayName:Qd,description:Xd,parameters:Zd,category:Yd,execute:fv,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var tu,ou,nu,ru,su,iu=g(()=>{"use strict";c();tu="system.cwd",ou="Current Directory",nu="Get the current working directory of the process.",ru="system",su={type:"object",properties:{}}});async function gv(r){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var wo,qi=g(()=>{"use strict";c();iu();P();wo={name:tu,displayName:ou,description:nu,parameters:su,category:ru,execute:gv}});var au,lu,cu,pu,mu,du=g(()=>{"use strict";c();au="system.disk_usage",lu="Disk Usage",cu="Get disk usage information for a given path or the root filesystem.",pu="system",mu={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});function Wi(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 hv(r){let t=r.path||(process.platform==="win32"?fu.tmpdir():"/");t=Kr.resolve(t);let o=process.platform==="win32";try{let n=uu.statfsSync(t),s=BigInt(n.blocks)*BigInt(n.bsize),i=BigInt(n.bavail)*BigInt(n.bsize),a=BigInt(n.bfree)*BigInt(n.bsize),l=s-a,p=s>0?Number(l*BigInt(100)/s):0;return JSON.stringify({path:t,filesystem:"statfs",size:Wi(Number(s)),used:Wi(Number(l)),available:Wi(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(n){try{if(o){let l=Kr.parse(t).root.replace(/\\$/,"")||"C:",p=`Get-PSDrive -Name ${l.replace(":","")} | Select-Object @{n='Drive';e={$_.Name+':'}},@{n='Used';e={$_.Used}},@{n='Free';e={$_.Free}},@{n='Total';e={$_.Used+$_.Free}} | ConvertTo-Json`,d=(0,Ui.execSync)(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),m=JSON.parse(d.trim()),u=m.Total||0,b=m.Free||0,h=m.Used||0,T=u>0?Math.round(h/u*100):0;return JSON.stringify({path:t,filesystem:m.Name||"NTFS",size:`${(u/1024**3).toFixed(1)}G`,used:`${(h/1024**3).toFixed(1)}G`,available:`${(b/1024**3).toFixed(1)}G`,usePercent:`${T}%`,mountedOn:m.Drive||`${l}`},null,2)}let s=(0,Ui.execSync)(`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 uu,fu,Kr,Ui,xo,Gi=g(()=>{"use strict";c();uu=x(require("fs"),1),fu=x(require("os"),1),Kr=x(require("path"),1),Ui=require("child_process");du();xo={name:au,displayName:lu,description:cu,parameters:mu,category:pu,execute:hv}});var gu={};te(gu,{systemCwdTool:()=>wo,systemDiskUsageTool:()=>xo,systemEnvTool:()=>bo,systemInfoTool:()=>yo,systemSetEnvTool:()=>To,systemToolsProject:()=>Bi});var Bi,zi=g(()=>{"use strict";c();Li();ji();Fi();qi();Gi();Li();ji();Fi();qi();Gi();Bi={manifest:{key:"system",name:"system-tools",displayName:"System",version:"1.0.0",description:"System tools for querying OS info, environment variables, working directory, and disk usage.",author:"Sajeer",tools:["system.info","system.env","system.set_env","system.cwd","system.disk_usage"],category:"system"},tools:[yo,bo,To,wo,xo],dependencies:{}}});var hu,yu,bu,Tu,wu,xu=g(()=>{"use strict";c();hu="http.get",yu="GET",bu="Make an HTTP GET request to a URL and return the response body.",Tu="http",wu={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 yv(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>vu?`${s}
72
+ ${n.substring(0,vu)}
73
73
 
74
74
  ... (truncated, total ${n.length} characters)`:`${s}
75
75
  ${n}`:`${s}
76
- ${n}`}var Tu,wo,Gi=g(()=>{"use strict";l();bu();_();Tu=1e5;wo={name:uu,displayName:fu,description:gu,parameters:yu,category:hu,execute:uv}});var wu,xu,vu,Cu,ku,Su=g(()=>{"use strict";l();wu="http.post",xu="POST",vu="Make an HTTP POST request to a URL with an optional body and return the response.",Cu="http",ku={type:"object",properties:{url:{type:"string",description:"The URL to request"},body:{type:"string",description:"Request body (JSON string or plain text)"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url"]}});async function fv(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>_u?`${i}
77
- ${s.substring(0,_u)}
76
+ ${n}`}var vu,vo,Hi=g(()=>{"use strict";c();xu();P();vu=1e5;vo={name:hu,displayName:yu,description:bu,parameters:wu,category:Tu,execute:yv}});var Cu,ku,Su,_u,Pu,Ru=g(()=>{"use strict";c();Cu="http.post",ku="POST",Su="Make an HTTP POST request to a URL with an optional body and return the response.",_u="http",Pu={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 bv(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>$u?`${i}
77
+ ${s.substring(0,$u)}
78
78
 
79
79
  ... (truncated, total ${s.length} characters)`:`${i}
80
- ${s}`}var _u,xo,Bi=g(()=>{"use strict";l();Su();_();_u=1e5;xo={name:wu,displayName:xu,description:vu,parameters:ku,category:Cu,execute:fv,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var Pu,Ru,$u,Eu,Du,Au=g(()=>{"use strict";l();Pu="http.put",Ru="PUT",$u="Make an HTTP PUT request to a URL with an optional body and return the response.",Eu="http",Du={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 gv(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>Mu?`${i}
81
- ${s.substring(0,Mu)}
80
+ ${s}`}var $u,Co,Ki=g(()=>{"use strict";c();Ru();P();$u=1e5;Co={name:Cu,displayName:ku,description:Su,parameters:Pu,category:_u,execute:bv,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var Eu,Du,Au,Mu,Nu,Ou=g(()=>{"use strict";c();Eu="http.put",Du="PUT",Au="Make an HTTP PUT request to a URL with an optional body and return the response.",Mu="http",Nu={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 Tv(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>Iu?`${i}
81
+ ${s.substring(0,Iu)}
82
82
 
83
83
  ... (truncated)`:`${i}
84
- ${s}`}var Mu,vo,zi=g(()=>{"use strict";l();Au();_();Mu=1e5;vo={name:Pu,displayName:Ru,description:$u,parameters:Du,category:Eu,execute:gv,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var Nu,Ou,Iu,ju,Lu,Fu=g(()=>{"use strict";l();Nu="http.delete",Ou="DELETE",Iu="Make an HTTP DELETE request to a URL and return the response.",ju="http",Lu={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 hv(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>qu?`${s}
85
- ${n.substring(0,qu)}
84
+ ${s}`}var Iu,ko,Ji=g(()=>{"use strict";c();Ou();P();Iu=1e5;ko={name:Eu,displayName:Du,description:Au,parameters:Nu,category:Mu,execute:Tv,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var Lu,ju,Fu,qu,Wu,Uu=g(()=>{"use strict";c();Lu="http.delete",ju="DELETE",Fu="Make an HTTP DELETE request to a URL and return the response.",qu="http",Wu={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 wv(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>Gu?`${s}
85
+ ${n.substring(0,Gu)}
86
86
 
87
87
  ... (truncated)`:`${s}
88
- ${n}`}var qu,Co,Hi=g(()=>{"use strict";l();Fu();_();qu=1e5;Co={name:Nu,displayName:Ou,description:Iu,parameters:Lu,category:ju,execute:hv,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var Wu,Uu,Gu,Bu,zu,Hu=g(()=>{"use strict";l();Wu="http.download",Uu="Download",Gu="Download a file from a URL and save it to a local path.",Bu="http",zu={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});async function yv(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=Ku.dirname(t);return ko.existsSync(i)||ko.mkdirSync(i,{recursive:!0}),ko.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var ko,Ku,So,Ki=g(()=>{"use strict";l();ko=x(require("fs"),1),Ku=x(require("path"),1);Hu();_();So={name:Wu,displayName:Uu,description:Gu,parameters:zu,category:Bu,execute:yv}});var Ju={};ee(Ju,{httpDeleteTool:()=>Co,httpDownloadTool:()=>So,httpGetTool:()=>wo,httpPostTool:()=>xo,httpPutTool:()=>vo,httpToolsProject:()=>Ji});var Ji,Vi=g(()=>{"use strict";l();Gi();Bi();zi();Hi();Ki();Gi();Bi();zi();Hi();Ki();Ji={manifest:{key:"http",name:"http-tools",displayName:"HTTP",version:"1.0.0",description:"HTTP tools for making GET, POST, PUT, DELETE requests and downloading files.",author:"Sajeer",tools:["http.get","http.post","http.put","http.delete","http.download"],category:"http"},tools:[wo,xo,vo,Co,So],dependencies:{}}});var Vu,Qu,Xu,Yu,Zu,ef=g(()=>{"use strict";l();Vu="github.graphql.execute",Qu="GitHub GraphQL",Xu=["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(" "),Yu="github",Zu={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 X(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=g(()=>{"use strict";l()});async function bv(r,e){let t=r.query,o=r.variables??{},n=await K(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:X(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 _o,Qi=g(()=>{"use strict";l();ef();_();Ne();xe();_o={name:Vu,displayName:Qu,description:Xu,parameters:Zu,category:Yu,execute:bv}});var tf,of,nf,rf,sf,af=g(()=>{"use strict";l();tf="github.contents.getText",of="Get Repo File (Text)",nf="Fetch file content (decoded text) via the GitHub Contents API.",rf="github",sf={type:"object",properties:{repo:{type:"string",description:"owner/name (e.g. octo/repo)"},path:{type:"string",description:"File path within the repo"},ref:{type:"string",description:"Branch, tag, or commit sha"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of decoded text to return; if exceeded, result is truncated with a footer."}},required:["repo","path"]}});async function Tv(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)}`:""}`;y(`[github.contents.getText] repo=${t} path=${o} ref=${n??""}`);let p=await fetch(c,{method:"GET",headers:X(s)}),d=await p.text();if(!p.ok)return`HTTP ${p.status} ${p.statusText}
90
- ${d}`;try{let f=JSON.parse(d)?.content;if(typeof f=="string"){let b=In.Buffer.from(f.replace(/\n/g,""),"base64").toString("utf8");if(i&&In.Buffer.byteLength(b,"utf8")>i){let h=In.Buffer.from(b,"utf8").subarray(0,i).toString("utf8"),T=`
91
- \u2026 [truncated, ${i} of ${In.Buffer.byteLength(b,"utf8")} bytes]`;return`HTTP ${p.status} ${p.statusText}
88
+ ${n}`}var Gu,So,Vi=g(()=>{"use strict";c();Uu();P();Gu=1e5;So={name:Lu,displayName:ju,description:Fu,parameters:Wu,category:qu,execute:wv,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var Bu,zu,Hu,Ku,Ju,Vu=g(()=>{"use strict";c();Bu="http.download",zu="Download",Hu="Download a file from a URL and save it to a local path.",Ku="http",Ju={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});async function xv(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=Qu.dirname(t);return _o.existsSync(i)||_o.mkdirSync(i,{recursive:!0}),_o.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var _o,Qu,Po,Qi=g(()=>{"use strict";c();_o=x(require("fs"),1),Qu=x(require("path"),1);Vu();P();Po={name:Bu,displayName:zu,description:Hu,parameters:Ju,category:Ku,execute:xv}});var Xu={};te(Xu,{httpDeleteTool:()=>So,httpDownloadTool:()=>Po,httpGetTool:()=>vo,httpPostTool:()=>Co,httpPutTool:()=>ko,httpToolsProject:()=>Xi});var Xi,Yi=g(()=>{"use strict";c();Hi();Ki();Ji();Vi();Qi();Hi();Ki();Ji();Vi();Qi();Xi={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:[vo,Co,ko,So,Po],dependencies:{}}});var Yu,Zu,ef,tf,of,nf=g(()=>{"use strict";c();Yu="github.graphql.execute",Zu="GitHub GraphQL",ef=["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(" "),tf="github",of={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 Y(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 Oe=g(()=>{"use strict";c()});async function vv(r,e){let t=r.query,o=r.variables??{},n=await V(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:Y(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 Ro,Zi=g(()=>{"use strict";c();nf();P();Oe();ve();Ro={name:Yu,displayName:Zu,description:ef,parameters:of,category:tf,execute:vv}});var rf,sf,af,lf,cf,pf=g(()=>{"use strict";c();rf="github.contents.getText",sf="Get Repo File (Text)",af="Fetch file content (decoded text) via the GitHub Contents API.",lf="github",cf={type:"object",properties:{repo:{type:"string",description:"owner/name (e.g. octo/repo)"},path:{type:"string",description:"File path within the repo"},ref:{type:"string",description:"Branch, tag, or commit sha"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of decoded text to return; if exceeded, result is truncated with a footer."}},required:["repo","path"]}});async function Cv(r,e){let t=r.repo,o=r.path,n=r.ref,s=await V(t,r.token,e?.githubTokenStore,e?.config?.credentials),i=r.maxBytes?Number(r.maxBytes):void 0,a=o.split("/").map(m=>encodeURIComponent(m)).join("/"),l=`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(l,{method:"GET",headers:Y(s)}),d=await p.text();if(!p.ok)return`HTTP ${p.status} ${p.statusText}
90
+ ${d}`;try{let u=JSON.parse(d)?.content;if(typeof u=="string"){let b=Fn.Buffer.from(u.replace(/\n/g,""),"base64").toString("utf8");if(i&&Fn.Buffer.byteLength(b,"utf8")>i){let h=Fn.Buffer.from(b,"utf8").subarray(0,i).toString("utf8"),T=`
91
+ \u2026 [truncated, ${i} of ${Fn.Buffer.byteLength(b,"utf8")} bytes]`;return`HTTP ${p.status} ${p.statusText}
92
92
  ${h}${T}`}return`HTTP ${p.status} ${p.statusText}
93
93
  ${b}`}}catch{}return`HTTP ${p.status} ${p.statusText}
94
- ${d}`}var In,Po,Xi=g(()=>{"use strict";l();af();_();Ne();xe();In=require("buffer");Po={name:tf,displayName:of,description:nf,parameters:sf,category:rf,execute:Tv}});var lf,cf,pf,mf,df,uf=g(()=>{"use strict";l();lf="github.pr.reviewThreads.list",cf="List PR Review Threads",pf="List PR review threads via GraphQL (optionally unresolved only).",mf="github",df={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 wv(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;y(`[github.pr.reviewThreads.list] repo=${t}/${o} pr=${n} unresolvedOnly=${i} first=${a} after=${c??""} commentsFirst=${p} includeMeta=${d}`);let f=await fetch("https://api.github.com/graphql",{method:"POST",headers:X(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 Fn,$o,ea=g(()=>{"use strict";c();pf();P();Oe();ve();Fn=require("buffer");$o={name:rf,displayName:sf,description:af,parameters:cf,category:lf,execute:Cv}});var mf,df,uf,ff,gf,hf=g(()=>{"use strict";c();mf="github.pr.reviewThreads.list",df="List PR Review Threads",uf="List PR review threads via GraphQL (optionally unresolved only).",ff="github",gf={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 kv(r,e){let[t,o]=String(r.repo).split("/"),n=Number(r.number),s=await V(r.repo,r.token,e?.githubTokenStore,e?.config?.credentials),i=!!r.unresolvedOnly,a=r.first?Number(r.first):100,l=r.after?String(r.after):void 0,p=r.commentsFirst?Number(r.commentsFirst):20,d=!!r.includeMeta;y(`[github.pr.reviewThreads.list] repo=${t}/${o} pr=${n} unresolvedOnly=${i} first=${a} after=${l??""} commentsFirst=${p} includeMeta=${d}`);let u=await fetch("https://api.github.com/graphql",{method:"POST",headers:Y(s,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
95
95
  repository(owner:$owner,name:$name){
96
96
  pullRequest(number:$number){
97
97
  headRefOid
@@ -101,41 +101,41 @@ ${d}`}var In,Po,Xi=g(()=>{"use strict";l();af();_();Ne();xe();In=require("buffer
101
101
  }
102
102
  }
103
103
  }
104
- }`,variables:{owner:t,name:o,number:n,first:a,after:c,commentsFirst:p}})}),b=await f.text();if(!f.ok)return`HTTP ${f.status} ${f.statusText}
105
- ${b}`;try{let h=JSON.parse(b);h&&Array.isArray(h.errors)&&h.errors.length>0&&y(`[github.pr.reviewThreads.list] errors=${h.errors.length}`);let T=h?.data?.repository?.pullRequest,k=T?.reviewThreads?.pageInfo??{hasNextPage:!1,endCursor:null},C=T?.reviewThreads?.nodes??[];if(i&&(C=C.filter(w=>w?.isResolved===!1)),d){let w={headRefOid:T?.headRefOid,threads:C,pageInfo:k};return`HTTP 200 OK
104
+ }`,variables:{owner:t,name:o,number:n,first:a,after:l,commentsFirst:p}})}),b=await u.text();if(!u.ok)return`HTTP ${u.status} ${u.statusText}
105
+ ${b}`;try{let h=JSON.parse(b);h&&Array.isArray(h.errors)&&h.errors.length>0&&y(`[github.pr.reviewThreads.list] errors=${h.errors.length}`);let T=h?.data?.repository?.pullRequest,C=T?.reviewThreads?.pageInfo??{hasNextPage:!1,endCursor:null},S=T?.reviewThreads?.nodes??[];if(i&&(S=S.filter(w=>w?.isResolved===!1)),d){let w={headRefOid:T?.headRefOid,threads:S,pageInfo:C};return`HTTP 200 OK
106
106
  ${JSON.stringify(w)}`}return`HTTP 200 OK
107
- ${JSON.stringify(C)}`}catch{return`HTTP ${f.status} ${f.statusText}
108
- ${b}`}}var Ro,Yi=g(()=>{"use strict";l();uf();Ne();_();xe();Ro={name:lf,displayName:cf,description:pf,parameters:df,category:mf,execute:wv}});var ff,gf,hf,yf,bf,Tf=g(()=>{"use strict";l();ff="github.pr.reviewThreads.resolve",gf="Resolve Review Thread",hf=["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(" "),yf="github",bf={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 xv(r,e){let t=String(r.threadId),o=await K(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:X(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 $o,Zi=g(()=>{"use strict";l();Tf();Ne();_();xe();$o={name:ff,displayName:gf,description:hf,parameters:bf,category:yf,execute:xv}});var wf,xf,vf,Cf,kf,Sf=g(()=>{"use strict";l();wf="github.pr.reviewComments.reply",xf="Reply to Review Comment",vf="Reply within an existing PR review thread to maintain continuity.",Cf="github",kf={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 vv(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`;y(`[github.pr.reviewComments.reply] repo=${t} inReplyTo=${n}`);let c=await fetch(a,{method:"POST",headers:X(i,{"Content-Type":"application/json"}),body:JSON.stringify({body:s})}),p=await c.text();return`HTTP ${c.status} ${c.statusText}
110
- ${p}`}var Eo,ea=g(()=>{"use strict";l();Sf();_();Ne();xe();Eo={name:wf,displayName:xf,description:vf,parameters:kf,category:Cf,execute:vv}});var _f,Pf,Rf,$f,Ef,Df=g(()=>{"use strict";l();_f="github.pr.diff.get",Pf="Get PR Diff",Rf="Fetch the unified diff for a pull request (text/patch).",$f="github",Ef={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of diff to return; if exceeded, result is truncated with a footer."}},required:["repo","number"]}});async function Cv(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}`;y(`[github.pr.diff.get] repo=${t} pr=${o}`);let a=await fetch(i,{method:"GET",headers:X(n,{Accept:"application/vnd.github.v3.diff"})}),c=await a.text();if(s&&zr.Buffer.byteLength(c,"utf8")>s){let p=zr.Buffer.from(c,"utf8").subarray(0,s).toString("utf8"),d=`
111
- \u2026 [truncated, ${s} of ${zr.Buffer.byteLength(c,"utf8")} bytes]`;return`HTTP ${a.status} ${a.statusText}
107
+ ${JSON.stringify(S)}`}catch{return`HTTP ${u.status} ${u.statusText}
108
+ ${b}`}}var Eo,ta=g(()=>{"use strict";c();hf();Oe();P();ve();Eo={name:mf,displayName:df,description:uf,parameters:gf,category:ff,execute:kv}});var yf,bf,Tf,wf,xf,vf=g(()=>{"use strict";c();yf="github.pr.reviewThreads.resolve",bf="Resolve Review Thread",Tf=["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(" "),wf="github",xf={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 Sv(r,e){let t=String(r.threadId),o=await V(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:Y(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 Do,oa=g(()=>{"use strict";c();vf();Oe();P();ve();Do={name:yf,displayName:bf,description:Tf,parameters:xf,category:wf,execute:Sv}});var Cf,kf,Sf,_f,Pf,Rf=g(()=>{"use strict";c();Cf="github.pr.reviewComments.reply",kf="Reply to Review Comment",Sf="Reply within an existing PR review thread to maintain continuity.",_f="github",Pf={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 _v(r,e){let t=String(r.repo),o=Number(r.number),n=Number(r.inReplyTo),s=String(r.body),i=await V(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 l=await fetch(a,{method:"POST",headers:Y(i,{"Content-Type":"application/json"}),body:JSON.stringify({body:s})}),p=await l.text();return`HTTP ${l.status} ${l.statusText}
110
+ ${p}`}var Ao,na=g(()=>{"use strict";c();Rf();P();Oe();ve();Ao={name:Cf,displayName:kf,description:Sf,parameters:Pf,category:_f,execute:_v}});var $f,Ef,Df,Af,Mf,Nf=g(()=>{"use strict";c();$f="github.pr.diff.get",Ef="Get PR Diff",Df="Fetch the unified diff for a pull request (text/patch).",Af="github",Mf={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of diff to return; if exceeded, result is truncated with a footer."}},required:["repo","number"]}});async function Pv(r,e){let t=String(r.repo),o=Number(r.number),n=await V(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:Y(n,{Accept:"application/vnd.github.v3.diff"})}),l=await a.text();if(s&&Jr.Buffer.byteLength(l,"utf8")>s){let p=Jr.Buffer.from(l,"utf8").subarray(0,s).toString("utf8"),d=`
111
+ \u2026 [truncated, ${s} of ${Jr.Buffer.byteLength(l,"utf8")} bytes]`;return`HTTP ${a.status} ${a.statusText}
112
112
  ${p}${d}`}return`HTTP ${a.status} ${a.statusText}
113
- ${c}`}var zr,Do,ta=g(()=>{"use strict";l();Df();Ne();_();xe();zr=require("buffer");Do={name:_f,displayName:Pf,description:Rf,parameters:Ef,category:$f,execute:Cv}});var Af,Mf,Nf,Of,If,jf=g(()=>{"use strict";l();Af="github.pr.files.list",Mf="List PR Files",Nf="List files changed in a PR with positions metadata.",Of="github",If={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 kv(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()}`:""}`;y(`[github.pr.files.list] repo=${t} pr=${o} perPage=${s??""} page=${i??""}`);let p=await fetch(c,{method:"GET",headers:X(n)}),d=await p.text();return`HTTP ${p.status} ${p.statusText}
114
- ${d}`}var Ao,oa=g(()=>{"use strict";l();jf();Ne();_();xe();Ao={name:Af,displayName:Mf,description:Nf,parameters:If,category:Of,execute:kv}});var Lf,Ff,qf,Wf,Uf,Gf=g(()=>{"use strict";l();Lf="github.pr.reviews.submit",Ff="Submit PR Review",qf="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",Wf="github",Uf={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 Sv(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`;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 d=await fetch(c,{method:"POST",headers:X(a,{"Content-Type":"application/json"}),body:JSON.stringify(p)}),m=await d.text();return`HTTP ${d.status} ${d.statusText}
115
- ${m}`}var Mo,na=g(()=>{"use strict";l();Gf();Ne();_();xe();Mo={name:Lf,displayName:Ff,description:qf,parameters:Uf,category:Wf,execute:Sv}});var Bf,zf,Hf,Kf,Jf,Vf=g(()=>{"use strict";l();Bf="github.issues.comments.create",zf="Create Issue/PR Comment",Hf="Create a comment on an issue or pull request (conversation tab).",Kf="github",Jf={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 _v(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`;y(`[github.issues.comments.create] repo=${t} number=${o}`);let a=await fetch(i,{method:"POST",headers:X(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),c=await a.text();return`HTTP ${a.status} ${a.statusText}
116
- ${c}`}var No,ra=g(()=>{"use strict";l();Vf();Ne();_();xe();No={name:Bf,displayName:zf,description:Hf,parameters:Jf,category:Kf,execute:_v}});var Qf={};ee(Qf,{githubContentsGetTextTool:()=>Po,githubGraphqlExecuteTool:()=>_o,githubIssuesCommentsCreateTool:()=>No,githubPrDiffGetTool:()=>Do,githubPrFilesListTool:()=>Ao,githubPrReviewCommentsReplyTool:()=>Eo,githubPrReviewThreadsListTool:()=>Ro,githubPrReviewThreadsResolveTool:()=>$o,githubPrReviewsSubmitTool:()=>Mo,githubToolsProject:()=>sa});var sa,ia=g(()=>{"use strict";l();Qi();Xi();Yi();Zi();ea();ta();oa();na();ra();Qi();Xi();Yi();Zi();ea();ta();oa();na();ra();sa={manifest:{key:"github",name:"github-tools",displayName:"GitHub",version:"1.0.0",description:"GitHub GraphQL/REST tools for PR threads, comments, and contents.",author:"Toolpack",tools:["github.graphql.execute","github.contents.getText","github.pr.reviewThreads.list","github.pr.reviewThreads.resolve","github.pr.reviewComments.reply","github.pr.diff.get","github.pr.files.list","github.pr.reviews.submit","github.issues.comments.create"],category:"github"},tools:[_o,Po,Ro,$o,Eo,Do,Ao,Mo,No],dependencies:{}}});var Xf,Yf,Zf,eg,tg,og=g(()=>{"use strict";l();Xf="web.fetch",Yf="Fetch",Zf="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).",eg="web",tg={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});function ng(r,e){let t=aa.load(r);t("script, style, nav, header, footer, aside, .advertisement, .ad, .sidebar").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||t('meta[property="og:title"]').attr("content")||"Untitled",n=t('meta[name="author"]').attr("content")||t('meta[property="article:author"]').attr("content")||t(".author").first().text().trim()||void 0,s=t('meta[property="article:published_time"]').attr("content")||t("time").first().attr("datetime")||t(".date, .published").first().text().trim()||void 0,i=["article","main",'[role="main"]',".content",".article-content",".post-content","#content"],a="";for(let b of i){let h=t(b).first();if(h.length>0&&(a=h.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let c=[];t("p").each((b,h)=>{let T=t(h).text().trim();T.length>50&&c.length<3&&c.push(T)});let p=c.join(`
113
+ ${l}`}var Jr,Mo,ra=g(()=>{"use strict";c();Nf();Oe();P();ve();Jr=require("buffer");Mo={name:$f,displayName:Ef,description:Df,parameters:Mf,category:Af,execute:Pv}});var Of,If,Lf,jf,Ff,qf=g(()=>{"use strict";c();Of="github.pr.files.list",If="List PR Files",Lf="List files changed in a PR with positions metadata.",jf="github",Ff={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 Rv(r,e){let t=String(r.repo),o=Number(r.number),n=await V(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 l=`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(l,{method:"GET",headers:Y(n)}),d=await p.text();return`HTTP ${p.status} ${p.statusText}
114
+ ${d}`}var No,sa=g(()=>{"use strict";c();qf();Oe();P();ve();No={name:Of,displayName:If,description:Lf,parameters:Ff,category:jf,execute:Rv}});var Wf,Uf,Gf,Bf,zf,Hf=g(()=>{"use strict";c();Wf="github.pr.reviews.submit",Uf="Submit PR Review",Gf="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",Bf="github",zf={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 $v(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 V(t,r.token,e?.githubTokenStore,e?.config?.credentials),l=`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 d=await fetch(l,{method:"POST",headers:Y(a,{"Content-Type":"application/json"}),body:JSON.stringify(p)}),m=await d.text();return`HTTP ${d.status} ${d.statusText}
115
+ ${m}`}var Oo,ia=g(()=>{"use strict";c();Hf();Oe();P();ve();Oo={name:Wf,displayName:Uf,description:Gf,parameters:zf,category:Bf,execute:$v}});var Kf,Jf,Vf,Qf,Xf,Yf=g(()=>{"use strict";c();Kf="github.issues.comments.create",Jf="Create Issue/PR Comment",Vf="Create a comment on an issue or pull request (conversation tab).",Qf="github",Xf={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 Ev(r,e){let t=String(r.repo),o=Number(r.number),n=String(r.body),s=await V(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:Y(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:n})}),l=await a.text();return`HTTP ${a.status} ${a.statusText}
116
+ ${l}`}var Io,aa=g(()=>{"use strict";c();Yf();Oe();P();ve();Io={name:Kf,displayName:Jf,description:Vf,parameters:Xf,category:Qf,execute:Ev}});var Zf={};te(Zf,{githubContentsGetTextTool:()=>$o,githubGraphqlExecuteTool:()=>Ro,githubIssuesCommentsCreateTool:()=>Io,githubPrDiffGetTool:()=>Mo,githubPrFilesListTool:()=>No,githubPrReviewCommentsReplyTool:()=>Ao,githubPrReviewThreadsListTool:()=>Eo,githubPrReviewThreadsResolveTool:()=>Do,githubPrReviewsSubmitTool:()=>Oo,githubToolsProject:()=>la});var la,ca=g(()=>{"use strict";c();Zi();ea();ta();oa();na();ra();sa();ia();aa();Zi();ea();ta();oa();na();ra();sa();ia();aa();la={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:[Ro,$o,Eo,Do,Ao,Mo,No,Oo,Io],dependencies:{}}});var eg,tg,og,ng,rg,sg=g(()=>{"use strict";c();eg="web.fetch",tg="Fetch",og="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).",ng="web",rg={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});function ig(r,e){let t=pa.load(r);t("script, style, nav, header, footer, aside, .advertisement, .ad, .sidebar").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||t('meta[property="og:title"]').attr("content")||"Untitled",n=t('meta[name="author"]').attr("content")||t('meta[property="article:author"]').attr("content")||t(".author").first().text().trim()||void 0,s=t('meta[property="article:published_time"]').attr("content")||t("time").first().attr("datetime")||t(".date, .published").first().text().trim()||void 0,i=["article","main",'[role="main"]',".content",".article-content",".post-content","#content"],a="";for(let b of i){let h=t(b).first();if(h.length>0&&(a=h.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let l=[];t("p").each((b,h)=>{let T=t(h).text().trim();T.length>50&&l.length<3&&l.push(T)});let p=l.join(`
117
117
 
118
- `)||a.substring(0,500),d=[];t("h2, h3").each((b,h)=>{let T=t(h).text().trim();T&&T.length>5&&T.length<200&&d.length<10&&d.push(T)});let m=a.split(/\s+/).length,f=a.split(/\s+/);return f.length>2e3&&(a=f.slice(0,2e3).join(" ")+"..."),{title:o,url:e,author:n,publishDate:s,excerpt:p.substring(0,1e3),mainContent:a.substring(0,1e4),keyPoints:d,wordCount:m}}function rg(r,e){let t=aa.load(r);t("script, style, nav, header, footer").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||"Untitled",n=t('meta[name="description"]').attr("content")||t('meta[property="og:description"]').attr("content")||"";return n||t("p").each((s,i)=>{let a=t(i).text().trim();a.length>50&&!n&&(n=a)}),n||(n=t("body").text().trim().replace(/\s+/g," ")),{title:o,url:e,snippet:n.substring(0,500)}}function sg(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 ig(r){return`# ${r.title}
118
+ `)||a.substring(0,500),d=[];t("h2, h3").each((b,h)=>{let T=t(h).text().trim();T&&T.length>5&&T.length<200&&d.length<10&&d.push(T)});let m=a.split(/\s+/).length,u=a.split(/\s+/);return u.length>2e3&&(a=u.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 ag(r,e){let t=pa.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 lg(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 cg(r){return`# ${r.title}
120
120
  URL: ${r.url}
121
121
 
122
- ${r.snippet}`}var aa,ag=g(()=>{"use strict";l();aa=x(require("cheerio"),1)});async function Pv(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=ng(c,e);return sg(p)}else if(t==="minimal"){let p=rg(c,e);return ig(p)}else return c.length>15e3?c.substring(0,15e3)+`
122
+ ${r.snippet}`}var pa,pg=g(()=>{"use strict";c();pa=x(require("cheerio"),1)});async function Dv(r){let e=r.url,t=r.extractionMode||"full",o=r.headers,n=r.timeout||3e4;if(y(`[web.fetch] execute url="${e}" mode=${t} timeout=${n}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let s=new AbortController,i=setTimeout(()=>s.abort(),n),a;try{a=await fetch(e,{method:"GET",headers:o||{},signal:s.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${n}ms`):p}finally{clearTimeout(i)}if(!a.ok)return`HTTP ${a.status} ${a.statusText}
123
+ ${await a.text()}`;let l=await a.text();if(t==="structured"){let p=ig(l,e);return lg(p)}else if(t==="minimal"){let p=ag(l,e);return cg(p)}else return l.length>15e3?l.substring(0,15e3)+`
124
124
 
125
- [TRUNCATED: showing 15K of ${c.length} total characters]`:c}var Oo,la=g(()=>{"use strict";l();og();ag();_();Oo={name:Xf,displayName:Yf,description:Zf,parameters:tg,category:eg,execute:Pv}});var lg,cg,pg,mg,dg,ug=g(()=>{"use strict";l();lg="web.search",cg="Search",pg="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.",mg="web",dg={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});function Ev(r,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=gg.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 Dv(r){if(r)switch(r){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function fg(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 Av(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 b=new AbortController,h=setTimeout(()=>b.abort(),r.timeout||3e4);return{signal:b.signal,clear:()=>clearTimeout(h)}};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:b,clear:h}=a(),T=Dv(s),k={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:c,query:t,max_results:o,include_answer:n,...T&&{days:T}}),signal:b};y(`[web.search] Tavily request=${JSON.stringify(k)}`);let C=await fetch("https://api.tavily.com/search",k).finally(h);if(C.ok){let w=await C.json();if(w.results&&w.results.length>0){let v=w.results.map(P=>({title:P.title,link:P.url,snippet:P.content}));return n&&w.answer?JSON.stringify({answer:w.answer,results:v},null,2):JSON.stringify(v,null,2)}}else fe(`[web.search] Tavily search failed with status ${C.status}`)}catch(b){fe(`[web.search] Tavily search failed, falling back: ${b}`)}}if(p)try{let{signal:b,clear:h}=a();if(n){let T=fg(s),k=T?`&freshness=${T}`:"",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:b}).finally(h);if(C.ok){let w=await C.json(),v=w.summarizer?.key;if(v&&w.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(),ne=w.web.results.slice(0,o).map(Z=>({title:Z.title,link:Z.url,snippet:Z.description})),B=R.summary?.map(Z=>Z.data).join(`
126
- `)||R.title;return JSON.stringify({answer:B,results:ne},null,2)}}if(w.web?.results){let P=w.web.results.slice(0,o).map(E=>({title:E.title,link:E.url,snippet:E.description}));return JSON.stringify(P,null,2)}}}else{let T=fg(s),k=T?`&freshness=${T}`:"",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:b}).finally(h);if(C.ok){let w=await C.json();if(w.web?.results&&w.web.results.length>0){let v=w.web.results.slice(0,o).map(P=>({title:P.title,link:P.url,snippet:P.description}));return JSON.stringify(v,null,2)}}}}catch(b){N(`[web.search] Brave search failed, falling back: ${b}`)}let{signal:d,clear:m}=a(),f;try{f=await fetch(Rv,{method:"POST",headers:{"User-Agent":$v,"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(b){throw b.name==="AbortError"?new Error(i):b}finally{m()}if(f.ok){let b=await f.text(),h=Ev(b,o);if(h.length>0)return JSON.stringify(h,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 gg,Rv,$v,Io,ca=g(()=>{"use strict";l();gg=x(require("cheerio"),1);ug();_();Rv="https://lite.duckduckgo.com/lite/",$v="Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1";Io={name:lg,displayName:cg,description:pg,parameters:dg,category:mg,execute:Av}});var hg,yg,bg,Tg,wg,xg=g(()=>{"use strict";l();hg="web.scrape",yg="Scrape",bg="Extract clean text content from a webpage. RECOMMENDED WORKFLOW: Use web.map first to see page structure, then use section parameter to extract specific sections. Strips scripts, styles, navigation, and other junk. By default, auto-detects and extracts the main article/content area.",Tg="web",wg={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Ov(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":Mv},signal:a.signal})}catch(h){throw h.name==="AbortError"?new Error(`Request timed out after ${i}ms`):h}finally{clearTimeout(c)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let d=await p.text(),m=kg.load(d);for(let h of Nv)m(h).remove();if(n==="tables"){let h=[];return m("table").each((T,k)=>{let C=[],w=[];m(k).find("th").each((v,P)=>{w.push(m(P).text().trim())}),m(k).find("tr").each((v,P)=>{let E=w.length>0?{}:[],j=m(P).find("td");j.length>0&&(j.each((R,ne)=>{let B=m(ne).text().trim();w.length>0&&w[R]?E[w[R]]=B:E.push(B)}),C.push(E))}),C.length>0&&h.push({id:`Table ${T+1}`,headers:w.length>0?w:void 0,rows:C})}),h.length===0?`No tables found on ${e}`:JSON.stringify(h,null,2)}let f="";if(o){let h=o.toLowerCase(),T=null,k=0;if(m("h1, h2, h3, h4, h5, h6").each((C,w)=>{if(m(w).text().toLowerCase().includes(h))return T=w,k=parseInt(w.tagName.charAt(1)),!1}),T){let C=m(T),w=[],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&&w.push(E),v=v.next()}w.length>0?(f=w.join(`
125
+ [TRUNCATED: showing 15K of ${l.length} total characters]`:l}var Lo,ma=g(()=>{"use strict";c();sg();pg();P();Lo={name:eg,displayName:tg,description:og,parameters:rg,category:ng,execute:Dv}});var mg,dg,ug,fg,gg,hg=g(()=>{"use strict";c();mg="web.search",dg="Search",ug="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.",fg="web",gg={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});function Nv(r,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=bg.load(r),o=[];return t("a.result-link").each((s,i)=>{if(o.length>=e)return;let a=t(i),l=a.text().trim(),p=a.attr("href"),d=a.siblings(".result-snippet").text().trim();d||(d=a.parent().text().replace(l,"").trim()),l&&p&&o.push({title:l,link:p,snippet:d.slice(0,200)})}),o}function Ov(r){if(r)switch(r){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function yg(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 Iv(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 b=new AbortController,h=setTimeout(()=>b.abort(),r.timeout||3e4);return{signal:b.signal,clear:()=>clearTimeout(h)}};if(!t)throw new Error("query is required");let l=e?.config?.webSearch?.tavilyApiKey??process.env.TOOLPACK_TAVILY_API_KEY,p=e?.config?.webSearch?.braveApiKey??process.env.TOOLPACK_BRAVE_API_KEY;if(l){y("[web.search] using Tavily API");try{let{signal:b,clear:h}=a(),T=Ov(s),C={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:l,query:t,max_results:o,include_answer:n,...T&&{days:T}}),signal:b};y(`[web.search] Tavily request=${JSON.stringify(C)}`);let S=await fetch("https://api.tavily.com/search",C).finally(h);if(S.ok){let w=await S.json();if(w.results&&w.results.length>0){let v=w.results.map(_=>({title:_.title,link:_.url,snippet:_.content}));return n&&w.answer?JSON.stringify({answer:w.answer,results:v},null,2):JSON.stringify(v,null,2)}}else ge(`[web.search] Tavily search failed with status ${S.status}`)}catch(b){ge(`[web.search] Tavily search failed, falling back: ${b}`)}}if(p)try{let{signal:b,clear:h}=a();if(n){let T=yg(s),C=T?`&freshness=${T}`:"",S=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(t)}&count=${Math.min(o,20)}&summary=1${C}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":p},signal:b}).finally(h);if(S.ok){let w=await S.json(),v=w.summarizer?.key;if(v&&w.web?.results){let{signal:_,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:_}).finally(E);if(j.ok){let R=await j.json(),re=w.web.results.slice(0,o).map(ee=>({title:ee.title,link:ee.url,snippet:ee.description})),H=R.summary?.map(ee=>ee.data).join(`
126
+ `)||R.title;return JSON.stringify({answer:H,results:re},null,2)}}if(w.web?.results){let _=w.web.results.slice(0,o).map(E=>({title:E.title,link:E.url,snippet:E.description}));return JSON.stringify(_,null,2)}}}else{let T=yg(s),C=T?`&freshness=${T}`:"",S=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(t)}&count=${Math.min(o,20)}${C}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":p},signal:b}).finally(h);if(S.ok){let w=await S.json();if(w.web?.results&&w.web.results.length>0){let v=w.web.results.slice(0,o).map(_=>({title:_.title,link:_.url,snippet:_.description}));return JSON.stringify(v,null,2)}}}}catch(b){I(`[web.search] Brave search failed, falling back: ${b}`)}let{signal:d,clear:m}=a(),u;try{u=await fetch(Av,{method:"POST",headers:{"User-Agent":Mv,"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(b){throw b.name==="AbortError"?new Error(i):b}finally{m()}if(u.ok){let b=await u.text(),h=Nv(b,o);if(h.length>0)return JSON.stringify(h,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 bg,Av,Mv,jo,da=g(()=>{"use strict";c();bg=x(require("cheerio"),1);hg();P();Av="https://lite.duckduckgo.com/lite/",Mv="Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1";jo={name:mg,displayName:dg,description:ug,parameters:gg,category:fg,execute:Iv}});var Tg,wg,xg,vg,Cg,kg=g(()=>{"use strict";c();Tg="web.scrape",wg="Scrape",xg="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.",vg="web",Cg={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Fv(r){let e=r.url,t=r.selector,o=r.section,n=r.format||"text",s=r.max_length||6e3,i=r.timeout||3e4;if(y(`[web.scrape] execute url="${e}" format=${n} selector=${t??"none"} section=${o??"none"} timeout=${i}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let a=new AbortController,l=setTimeout(()=>a.abort(),i),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":Lv},signal:a.signal})}catch(h){throw h.name==="AbortError"?new Error(`Request timed out after ${i}ms`):h}finally{clearTimeout(l)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let d=await p.text(),m=Pg.load(d);for(let h of jv)m(h).remove();if(n==="tables"){let h=[];return m("table").each((T,C)=>{let S=[],w=[];m(C).find("th").each((v,_)=>{w.push(m(_).text().trim())}),m(C).find("tr").each((v,_)=>{let E=w.length>0?{}:[],j=m(_).find("td");j.length>0&&(j.each((R,re)=>{let H=m(re).text().trim();w.length>0&&w[R]?E[w[R]]=H:E.push(H)}),S.push(E))}),S.length>0&&h.push({id:`Table ${T+1}`,headers:w.length>0?w:void 0,rows:S})}),h.length===0?`No tables found on ${e}`:JSON.stringify(h,null,2)}let u="";if(o){let h=o.toLowerCase(),T=null,C=0;if(m("h1, h2, h3, h4, h5, h6").each((S,w)=>{if(m(w).text().toLowerCase().includes(h))return T=w,C=parseInt(w.tagName.charAt(1)),!1}),T){let S=m(T),w=[],v=S.next();for(;v.length>0;){let _=v.prop("tagName")?.toLowerCase();if(_&&/^h[1-6]$/.test(_)&&parseInt(_.charAt(1))<=C)break;let E=v.text().trim();E&&w.push(E),v=v.next()}w.length>0?(u=w.join(`
127
127
 
128
- `).replace(/\s+/g," ").trim(),f=`[Section: "${o}"]
128
+ `).replace(/\s+/g," ").trim(),u=`[Section: "${o}"]
129
129
 
130
- ${f}`):f=`[Note: Found heading "${o}" but no content below it. Falling back to full page.]
130
+ ${u}`):u=`[Note: Found heading "${o}" but no content below it. Falling back to full page.]
131
131
 
132
- `}else f=`[Note: Section "${o}" not found. Falling back to full page.]
132
+ `}else u=`[Note: Section "${o}" not found. Falling back to full page.]
133
133
 
134
- `}if(!f||f.includes("Falling back to full page"))if(f&&f.includes("Falling back to full page")&&(f=""),t){let h=m(t);if(h.length>0)f=h.text().replace(/\s+/g," ").trim();else{for(let T of vg){let k=m(T);if(k.length>0){let C=k.text().replace(/\s+/g," ").trim();if(C.length>Cg){f=C;break}}}if(f)f=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
134
+ `}if(!u||u.includes("Falling back to full page"))if(u&&u.includes("Falling back to full page")&&(u=""),t){let h=m(t);if(h.length>0)u=h.text().replace(/\s+/g," ").trim();else{for(let T of Sg){let C=m(T);if(C.length>0){let S=C.text().replace(/\s+/g," ").trim();if(S.length>_g){u=S;break}}}if(u)u=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
135
135
 
136
- ${f}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let h of vg){let T=m(h);if(T.length>0){let k=T.text().replace(/\s+/g," ").trim();if(k.length>Cg){f=k;break}}}if(f||(f=m("body").text().replace(/\s+/g," ").trim(),f&&(f=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
136
+ ${u}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let h of Sg){let T=m(h);if(T.length>0){let C=T.text().replace(/\s+/g," ").trim();if(C.length>_g){u=C;break}}}if(u||(u=m("body").text().replace(/\s+/g," ").trim(),u&&(u=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
137
137
 
138
- ${f}`)),!f)return`Could not extract any content from ${e}`;if(f.length>s){let h=f.substring(0,s);return`[Warning: Content exceeds ${s} chars (actual: ${f.length} chars). Showing first ${s} chars only.]
138
+ ${u}`)),!u)return`Could not extract any content from ${e}`;if(u.length>s){let h=u.substring(0,s);return`[Warning: Content exceeds ${s} chars (actual: ${u.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
 
@@ -143,20 +143,20 @@ Page content from ${e}:
143
143
 
144
144
  ${h}
145
145
 
146
- ... [Content truncated. ${f.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
146
+ ... [Content truncated. ${u.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
147
147
 
148
- ${f}`}var kg,Mv,Nv,vg,Cg,jo,pa=g(()=>{"use strict";l();kg=x(require("cheerio"),1);xg();_();Mv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Nv=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],vg=["article","main",".content","#content",'[role="main"]',"body"],Cg=200;jo={name:hg,displayName:yg,description:bg,parameters:wg,category:Tg,execute:Ov}});var Sg,_g,Pg,Rg,$g,Eg=g(()=>{"use strict";l();Sg="web.extract_links",_g="Extract Links",Pg="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Rg="web",$g={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function jv(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":Iv},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=Dg.load(a),p=new URL(e),d=[];return c("a[href]").each((m,f)=>{let b=c(f),h=b.attr("href");if(!h)return;let T;try{T=new URL(h,e).toString()}catch{return}if(T.startsWith("javascript:")||T.startsWith("mailto:")||T.startsWith("tel:"))return;let k=b.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(T).hostname!==p.hostname)return}catch{return}else if(!T.includes(t))return}d.push({text:k,url:T})}),d.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(d,null,2)}var Dg,Iv,Lo,ma=g(()=>{"use strict";l();Dg=x(require("cheerio"),1);Eg();Iv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Lo={name:Sg,displayName:_g,description:Pg,parameters:$g,category:Rg,execute:jv}});var Ag,Mg,Ng,Og,Ig,jg=g(()=>{"use strict";l();Ag="web.map",Mg="Map",Ng="Extract the structure/outline of a webpage by returning all headings (h1-h6). Use this FIRST when you need to understand what sections exist on a page before scraping specific content. Returns a lightweight outline showing the page hierarchy.",Og="web",Ig={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Fv(r){let e=r.url,t=r.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=new AbortController,n=setTimeout(()=>o.abort(),t),s;try{s=await fetch(e,{method:"GET",headers:{"User-Agent":Lv},signal:o.signal})}catch(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=Lg.load(i),c=[];if(a("h1, h2, h3, h4, h5, h6").each((d,m)=>{let f=m.tagName.toLowerCase(),b=parseInt(f.charAt(1)),h=a(m).text().trim();h&&c.push({level:b,text:h})}),c.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
148
+ ${u}`}var Pg,Lv,jv,Sg,_g,Fo,ua=g(()=>{"use strict";c();Pg=x(require("cheerio"),1);kg();P();Lv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",jv=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Sg=["article","main",".content","#content",'[role="main"]',"body"],_g=200;Fo={name:Tg,displayName:wg,description:xg,parameters:Cg,category:vg,execute:Fv}});var Rg,$g,Eg,Dg,Ag,Mg=g(()=>{"use strict";c();Rg="web.extract_links",$g="Extract Links",Eg="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",Dg="web",Ag={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Wv(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":qv},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(),l=Ng.load(a),p=new URL(e),d=[];return l("a[href]").each((m,u)=>{let b=l(u),h=b.attr("href");if(!h)return;let T;try{T=new URL(h,e).toString()}catch{return}if(T.startsWith("javascript:")||T.startsWith("mailto:")||T.startsWith("tel:"))return;let C=b.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(T).hostname!==p.hostname)return}catch{return}else if(!T.includes(t))return}d.push({text:C,url:T})}),d.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(d,null,2)}var Ng,qv,qo,fa=g(()=>{"use strict";c();Ng=x(require("cheerio"),1);Mg();qv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";qo={name:Rg,displayName:$g,description:Eg,parameters:Ag,category:Dg,execute:Wv}});var Og,Ig,Lg,jg,Fg,qg=g(()=>{"use strict";c();Og="web.map",Ig="Map",Lg="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.",jg="web",Fg={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Gv(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":Uv},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=Wg.load(i),l=[];if(a("h1, h2, h3, h4, h5, h6").each((d,m)=>{let u=m.tagName.toLowerCase(),b=parseInt(u.charAt(1)),h=a(m).text().trim();h&&l.push({level:b,text:h})}),l.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 d of c){let m=" ".repeat(d.level-1);p+=`${m}${"#".repeat(d.level)} ${d.text}
151
- `}return p}var Lg,Lv,Fo,da=g(()=>{"use strict";l();Lg=x(require("cheerio"),1);jg();Lv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Fo={name:Ag,displayName:Mg,description:Ng,parameters:Ig,category:Og,execute:Fv}});var Fg,qg,Wg,Ug,Gg,Bg=g(()=>{"use strict";l();Fg="web.metadata",qg="Extract Metadata",Wg="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",Ug="web",Gg={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function Wv(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":qv},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=zg.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:",""),f=a(d).attr("content");m&&f&&(c.openGraph[m]=f)}),a('meta[name^="twitter:"]').each((p,d)=>{let m=a(d).attr("name")?.replace("twitter:",""),f=a(d).attr("content");m&&f&&(c.twitter[m]=f)}),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 zg,qv,qo,ua=g(()=>{"use strict";l();zg=x(require("cheerio"),1);Bg();qv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";qo={name:Fg,displayName:qg,description:Wg,parameters:Gg,category:Ug,execute:Wv}});var Hg,Kg,Jg,Vg,Qg,Xg=g(()=>{"use strict";l();Hg="web.sitemap",Kg="Extract Sitemap",Jg="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Vg="web",Qg={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function fa(r,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(r,{method:"GET",headers:{"User-Agent":Uv},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function Gv(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 fa(n,o),!i.ok&&s&&(n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await fa(n,o))}catch(p){if(s)n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await fa(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=Yg.load(a,{xmlMode:!0}),d=p("sitemap > loc");if(d.length>0)return d.each((f,b)=>{c.length>=t||c.push({loc:p(b).text()})}),JSON.stringify({type:"sitemapindex",urls:c},null,2);p("urlset > url").each((f,b)=>{if(c.length>=t)return;let h=p(b);c.push({loc:h.children("loc").text(),lastmod:h.children("lastmod").text()||void 0,priority:h.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 f=m.substring(6).trim();c.push({loc:new URL(f,n).toString()})}}}return JSON.stringify(c,null,2)}var Yg,Uv,Wo,ga=g(()=>{"use strict";l();Yg=x(require("cheerio"),1);Xg();Uv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Wo={name:Hg,displayName:Kg,description:Jg,parameters:Qg,category:Vg,execute:Gv}});var Zg,eh,th,oh,nh,rh=g(()=>{"use strict";l();Zg="web.feed",eh="Extract Feed",th="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",oh="web",nh={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 sh(){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 ih=g(()=>{"use strict";l()});async function Bv(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 sh();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 Uo,ha=g(()=>{"use strict";l();rh();ih();Uo={name:Zg,displayName:eh,description:th,parameters:nh,category:oh,execute:Bv}});var ah,lh,ch,ph,mh,dh=g(()=>{"use strict";l();ah="web.screenshot",lh="Screenshot",ch="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",ph="web",mh={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 uh(){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 fh=g(()=>{"use strict";l()});async function Hv(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 uh()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(zv),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 zv,Go,ya=g(()=>{"use strict";l();dh();fh();zv="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:ah,displayName:lh,description:ch,parameters:mh,category:ph,execute:Hv}});var gh={};ee(gh,{webExtractLinksTool:()=>Lo,webFeedTool:()=>Uo,webFetchTool:()=>Oo,webMapTool:()=>Fo,webMetadataTool:()=>qo,webScrapeTool:()=>jo,webScreenshotTool:()=>Go,webSearchTool:()=>Io,webSitemapTool:()=>Wo,webToolsProject:()=>ba});var ba,Ta=g(()=>{"use strict";l();la();ca();pa();ma();da();ua();ga();ha();ya();la();ca();pa();ma();da();ua();ga();ha();ya();ba={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:[Oo,Io,jo,Lo,Fo,qo,Wo,Uo,Go],dependencies:{cheerio:"^1.0.0-rc.12"}}});var hh,yh,bh,Th,wh,xh=g(()=>{"use strict";l();hh="coding.find_symbol",yh="Find Symbol",bh="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Th="coding",wh={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});function Hr(r){let e=(0,vh.extname)(r).toLowerCase();return Kv[e]||"unknown"}var vh,Kv,wa=g(()=>{"use strict";l();vh=require("path"),Kv={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});var wt,We,nt,kh,Ch,xa,Jv,Kr,Sh=g(()=>{"use strict";l();wt=x(require("web-tree-sitter"),1),We=x(require("fs"),1),nt=x(require("path"),1),kh=x(require("os"),1),Ch=wt.default||wt.Parser||wt,xa=nt.join(kh.homedir(),".toolpack-sdk","grammars"),Jv=nt.resolve(__dirname,"../../grammars"),Kr=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Ch.init({locateFile(e,t){return nt.join(__dirname,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let o=await this.resolveGrammarPath(e),s=await(wt.Language||Ch.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=nt.resolve(__dirname,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(We.existsSync(o))return o;let n=nt.join(Jv,t);if(We.existsSync(n))return n;let s=nt.join(xa,t);return We.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){We.existsSync(xa)||We.mkdirSync(xa,{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);We.writeFileSync(t,i)}}});var jn,_h,Ph,Vv,Jr,Rh=g(()=>{"use strict";l();jn=x(require("web-tree-sitter"),1),_h=x(require("fs"),1),Ph=x(require("crypto"),1);wa();Sh();Vv=jn.default||jn.Parser||jn,Jr=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Kr}hash(e){return Ph.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:_h.readFileSync(e,"utf-8"),n=this.hash(o),s=this.treeCache.get(e),i=Hr(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 Vv),this.parser.setLanguage(a);let c;return s?(s.tree&&s.tree.delete(),c=this.parser.parse(o)):c=this.parser.parse(o),this.treeCache.set(e,{tree:c,language:i,contentHash:n,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:c,language:i,grammar:a}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[o,n]of this.treeCache.entries())n.lastAccessed<t&&(t=n.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});var $h,va,Oe,Vr,Eh=g(()=>{"use strict";l();$h=require("@babel/parser"),va=x(require("@babel/traverse"),1),Oe=va.default||va,Vr=class{parseCode(e){return(0,$h.parse)(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,o){let n=[];try{let s=this.parseCode(e.content),i=e.filePath;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,f=i[d-1]||"";n.push({file:e.filePath,line:d,column:m,context:f.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(`
150
+ `;for(let d of l){let m=" ".repeat(d.level-1);p+=`${m}${"#".repeat(d.level)} ${d.text}
151
+ `}return p}var Wg,Uv,Wo,ga=g(()=>{"use strict";c();Wg=x(require("cheerio"),1);qg();Uv="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";Wo={name:Og,displayName:Ig,description:Lg,parameters:Fg,category:jg,execute:Gv}});var Ug,Gg,Bg,zg,Hg,Kg=g(()=>{"use strict";c();Ug="web.metadata",Gg="Extract Metadata",Bg="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",zg="web",Hg={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function zv(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":Bv},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=Jg.load(i),l={title:a("title").text()||"",description:a('meta[name="description"]').attr("content")||a('meta[property="og:description"]').attr("content")||"",author:a('meta[name="author"]').attr("content")||"",openGraph:{},twitter:{},jsonLd:[]};return a('meta[property^="og:"]').each((p,d)=>{let m=a(d).attr("property")?.replace("og:",""),u=a(d).attr("content");m&&u&&(l.openGraph[m]=u)}),a('meta[name^="twitter:"]').each((p,d)=>{let m=a(d).attr("name")?.replace("twitter:",""),u=a(d).attr("content");m&&u&&(l.twitter[m]=u)}),a('script[type="application/ld+json"]').each((p,d)=>{let m=a(d).html();if(m)try{l.jsonLd.push(JSON.parse(m))}catch{}}),JSON.stringify(l,null,2)}var Jg,Bv,Uo,ha=g(()=>{"use strict";c();Jg=x(require("cheerio"),1);Kg();Bv="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:Ug,displayName:Gg,description:Bg,parameters:Hg,category:zg,execute:zv}});var Vg,Qg,Xg,Yg,Zg,eh=g(()=>{"use strict";c();Vg="web.sitemap",Qg="Extract Sitemap",Xg="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Yg="web",Zg={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});async function ya(r,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(r,{method:"GET",headers:{"User-Agent":Hv},signal:t.signal})}catch(n){throw n.name==="AbortError"?new Error(`Request timed out after ${e}ms`):n}finally{clearTimeout(o)}}async function Kv(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 ya(n,o),!i.ok&&s&&(n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ya(n,o))}catch(p){if(s)n=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await ya(n,o);else throw p}if(!i||!i.ok)throw new Error(`Failed to fetch sitemap or robots.txt from ${e}`);let a=await i.text(),l=[];if(n.endsWith(".xml")||a.trim().startsWith("<")){let p=th.load(a,{xmlMode:!0}),d=p("sitemap > loc");if(d.length>0)return d.each((u,b)=>{l.length>=t||l.push({loc:p(b).text()})}),JSON.stringify({type:"sitemapindex",urls:l},null,2);p("urlset > url").each((u,b)=>{if(l.length>=t)return;let h=p(b);l.push({loc:h.children("loc").text(),lastmod:h.children("lastmod").text()||void 0,priority:h.children("priority").text()||void 0})})}else{let p=a.split(`
152
+ `);for(let d of p){if(l.length>=t)break;let m=d.trim();if(m.toLowerCase().startsWith("sitemap:"))l.push({loc:m.substring(8).trim()});else if(m.toLowerCase().startsWith("allow:")){let u=m.substring(6).trim();l.push({loc:new URL(u,n).toString()})}}}return JSON.stringify(l,null,2)}var th,Hv,Go,ba=g(()=>{"use strict";c();th=x(require("cheerio"),1);eh();Hv="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:Vg,displayName:Qg,description:Xg,parameters:Zg,category:Yg,execute:Kv}});var oh,nh,rh,sh,ih,ah=g(()=>{"use strict";c();oh="web.feed",nh="Extract Feed",rh="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",sh="web",ih={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 lh(){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 ch=g(()=>{"use strict";c()});async function Jv(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 lh();n.options={...n.options,timeout:o};try{let s=await n.parseURL(e),i=s.items.slice(0,t).map(a=>({title:a.title,link:a.link,published:a.pubDate||a.isoDate,summary:a.contentSnippet||a.content}));return JSON.stringify({feedTitle:s.title,feedDescription:s.description,entries:i},null,2)}catch(s){throw new Error(`Failed to parse feed from ${e}: ${s.message}`)}}var Bo,Ta=g(()=>{"use strict";c();ah();ch();Bo={name:oh,displayName:nh,description:rh,parameters:ih,category:sh,execute:Jv}});var ph,mh,dh,uh,fh,gh=g(()=>{"use strict";c();ph="web.screenshot",mh="Screenshot",dh="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",uh="web",fh={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 hh(){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 yh=g(()=>{"use strict";c()});async function Qv(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 hh()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(Vv),await a.setViewport({width:o?.width||1280,height:o?.height||800}),await a.goto(e,{waitUntil:"networkidle2",timeout:n}),t==="png"){let l=await a.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(l)?p=l.toString("base64"):p=Buffer.from(l).toString("base64"),`data:image/png;base64,${p}`}else return await a.content()}finally{await i.close()}}var Vv,zo,wa=g(()=>{"use strict";c();gh();yh();Vv="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:ph,displayName:mh,description:dh,parameters:fh,category:uh,execute:Qv}});var bh={};te(bh,{webExtractLinksTool:()=>qo,webFeedTool:()=>Bo,webFetchTool:()=>Lo,webMapTool:()=>Wo,webMetadataTool:()=>Uo,webScrapeTool:()=>Fo,webScreenshotTool:()=>zo,webSearchTool:()=>jo,webSitemapTool:()=>Go,webToolsProject:()=>xa});var xa,va=g(()=>{"use strict";c();ma();da();ua();fa();ga();ha();ba();Ta();wa();ma();da();ua();fa();ga();ha();ba();Ta();wa();xa={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:[Lo,jo,Fo,qo,Wo,Uo,Go,Bo,zo],dependencies:{cheerio:"^1.0.0-rc.12"}}});var Th,wh,xh,vh,Ch,kh=g(()=>{"use strict";c();Th="coding.find_symbol",wh="Find Symbol",xh="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",vh="coding",Ch={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});function Vr(r){let e=(0,Sh.extname)(r).toLowerCase();return Xv[e]||"unknown"}var Sh,Xv,Ca=g(()=>{"use strict";c();Sh=require("path"),Xv={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});var vt,Ge,st,Ph,_h,ka,Yv,Qr,Rh=g(()=>{"use strict";c();vt=x(require("web-tree-sitter"),1),Ge=x(require("fs"),1),st=x(require("path"),1),Ph=x(require("os"),1),_h=vt.default||vt.Parser||vt,ka=st.join(Ph.homedir(),".toolpack-sdk","grammars"),Yv=st.resolve(__dirname,"../../grammars"),Qr=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await _h.init({locateFile(e,t){return st.join(__dirname,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let o=await this.resolveGrammarPath(e),s=await(vt.Language||_h.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=st.resolve(__dirname,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(Ge.existsSync(o))return o;let n=st.join(Yv,t);if(Ge.existsSync(n))return n;let s=st.join(ka,t);return Ge.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){Ge.existsSync(ka)||Ge.mkdirSync(ka,{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);Ge.writeFileSync(t,i)}}});var qn,$h,Eh,Zv,Xr,Dh=g(()=>{"use strict";c();qn=x(require("web-tree-sitter"),1),$h=x(require("fs"),1),Eh=x(require("crypto"),1);Ca();Rh();Zv=qn.default||qn.Parser||qn,Xr=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Qr}hash(e){return Eh.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:$h.readFileSync(e,"utf-8"),n=this.hash(o),s=this.treeCache.get(e),i=Vr(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 Zv),this.parser.setLanguage(a);let l;return s?(s.tree&&s.tree.delete(),l=this.parser.parse(o)):l=this.parser.parse(o),this.treeCache.set(e,{tree:l,language:i,contentHash:n,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:l,language:i,grammar:a}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[o,n]of this.treeCache.entries())n.lastAccessed<t&&(t=n.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});var Ah,Sa,Ie,Yr,Mh=g(()=>{"use strict";c();Ah=require("@babel/parser"),Sa=x(require("@babel/traverse"),1),Ie=Sa.default||Sa,Yr=class{parseCode(e){return(0,Ah.parse)(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,o){let n=[];try{let s=this.parseCode(e.content),i=e.filePath;Ie(s,{FunctionDeclaration(a){a.node.id?.name===t&&(!o||o==="function")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(a){a.node.id?.name===t&&(!o||o==="class")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(a){if(a.node.id.type==="Identifier"&&a.node.id.name===t){let l=a.parent,p=l.type==="VariableDeclaration"?l.kind:"variable";(!o||o===p||o==="variable")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(a){a.node.id.name===t&&(!o||o==="interface")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(a){a.node.id.name===t&&(!o||o==="type")&&n.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return n}async getSymbols(e,t){let o=[];try{let n=this.parseCode(e.content);Ie(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);Ie(o,{ImportDeclaration(n){let s=n.node.source.value,i=[],a="side-effect";for(let l of n.node.specifiers)if(l.type==="ImportDefaultSpecifier")i.push(l.local.name),a="default";else if(l.type==="ImportNamespaceSpecifier")i.push(`* as ${l.local.name}`),a="namespace";else if(l.type==="ImportSpecifier"){let p=l.imported.type==="Identifier"?l.imported.name:l.imported.value,d=l.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);Ie(a,{Identifier(l){if(l.node.name===t){let p=l.isFunctionDeclaration()||l.isClassDeclaration()||l.parent.type==="VariableDeclarator"&&l.parent.id===l.node||l.parent.type==="TSInterfaceDeclaration"&&l.parent.id===l.node||l.parent.type==="TSTypeAliasDeclaration"&&l.parent.id===l.node;if(!p||o){let d=l.node.loc?.start.line||0,m=l.node.loc?.start.column||0,u=i[d-1]||"";n.push({file:e.filePath,line:d,column:m,context:u.trim(),isDeclaration:p})}}}})}catch{}return n}async getSymbolAtPosition(e,t,o){try{let n=this.parseCode(e.content),s=null;return Ie(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 Ie(o,{FunctionDeclaration(i){i.node.id?.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t},i.stop())},ClassDeclaration(i){i.node.id?.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t},i.stop())},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let a=i.parent,l=a.type==="VariableDeclaration"?a.kind:"variable";s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:l,name:t},i.stop()}},TSInterfaceDeclaration(i){i.node.id.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t},i.stop())},TSTypeAliasDeclaration(i){i.node.id.name===t&&(s={file:n,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t},i.stop())}}),s}catch{return null}}async getDiagnostics(e){try{return this.parseCode(e.content),[]}catch(t){return[{message:t.message,line:t.loc?.line||0,column:t.loc?.column||0,severity:"error"}]}}async getExports(e){let t=[];try{let o=this.parseCode(e.content);Ie(o,{ExportNamedDeclaration(n){if(n.node.declaration)if(n.node.declaration.type==="VariableDeclaration")for(let s of n.node.declaration.declarations)s.id.type==="Identifier"&&t.push({name:s.id.name,kind:"variable",line:s.loc?.start.line||0,column:s.loc?.start.column||0});else n.node.declaration.type==="FunctionDeclaration"&&n.node.declaration.id?t.push({name:n.node.declaration.id.name,kind:"function",line:n.node.declaration.loc?.start.line||0,column:n.node.declaration.loc?.start.column||0}):n.node.declaration.type==="ClassDeclaration"&&n.node.declaration.id&&t.push({name:n.node.declaration.id.name,kind:"class",line:n.node.declaration.loc?.start.line||0,column:n.node.declaration.loc?.start.column||0});else if(n.node.specifiers)for(let s of n.node.specifiers)s.exported.type==="Identifier"&&t.push({name:s.exported.name,kind:"export",line:s.loc?.start.line||0,column:s.loc?.start.column||0})},ExportDefaultDeclaration(n){let s="default",i="default";n.node.declaration.type==="ClassDeclaration"&&n.node.declaration.id?(s=n.node.declaration.id.name,i="class"):n.node.declaration.type==="FunctionDeclaration"&&n.node.declaration.id?(s=n.node.declaration.id.name,i="function"):n.node.declaration.type==="Identifier"&&(s=n.node.declaration.name,i="variable"),t.push({name:s,kind:i,line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}})}catch{}return t}async getOutline(e){let t=[];try{return(await this.getSymbols(e)).map(n=>({name:n.name,kind:n.kind,line:n.line,column:n.column,children:[]}))}catch{}return t}async extractFunction(e,t,o,n,s,i){let a=e.content.split(`
154
+ `),l=Math.max(0,t-1),p=Math.min(a.length,n),d=a.slice(l,p).join(`
155
155
  `),m=`
156
156
  function ${i}() {
157
157
  ${d}
158
158
  }
159
- `,f=`${i}();`;return{newFunction:m,replacementCall:f}}async getCallHierarchy(e,t,o){try{let n=this.parseCode(e.content),s=e.filePath,i=null,a="",c=0,p=0;if(Oe(n,{Function(h){let T=h.node.loc;T&&T.start.line<=t&&T.end&&T.end.line>=t&&(i=h,c=T.start.line,p=T.start.column,h.node.type==="FunctionDeclaration"&&h.node.id?a=h.node.id.name:h.parent.type==="VariableDeclarator"&&h.parent.id.type==="Identifier"?a=h.parent.id.name:h.parent.type==="ClassMethod"||h.parent.type==="ObjectMethod"?h.parent.key.type==="Identifier"&&(a=h.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let d=[],m=[];Oe(n,{CallExpression(h){let T=h.node.loc;if(!T||T.start.line<c||T.end&&T.end.line>c+1e3)return;let k=!1,C=h;for(;C;){if(C.isFunction()&&C.node.type==="FunctionDeclaration"&&C.node.id?.name===a){k=!0;break}C=C.parentPath}if(!k)return;let w=h.node.callee,v="<unknown>";w.type==="Identifier"?v=w.name:w.type==="MemberExpression"&&w.property.type==="Identifier"&&(v=w.property.name),v!=="<unknown>"&&m.push({file:s,name:v,line:h.node.loc?.start.line||0,column:h.node.loc?.start.column||0})}}),Oe(n,{CallExpression(h){let T=h.node.callee,k=!1;if((T.type==="Identifier"&&T.name===a||T.type==="MemberExpression"&&T.property.type==="Identifier"&&T.property.name===a)&&(k=!0),k){let C="<global>",w=h;for(;w;){if(w.isFunction()){w.node.type==="FunctionDeclaration"&&w.node.id?C=w.node.id.name:w.parent.type==="VariableDeclarator"&&w.parent.id.type==="Identifier"?C=w.parent.id.name:(w.parent.type==="ClassMethod"||w.parent.type==="ObjectMethod")&&w.parent.key.type==="Identifier"&&(C=w.parent.key.name);break}w=w.parentPath}d.push({file:s,name:C,line:h.node.loc?.start.line||0,column:h.node.loc?.start.column||0})}}});let f=[...new Map(d.map(h=>[`${h.name}:${h.line}`,h])).values()],b=[...new Map(m.map(h=>[`${h.name}:${h.line}`,h])).values()];return{file:s,name:a,line:c,column:p,callers:f,callees:b}}catch{return null}}}});function Re(r,e){Ca[r]=e}var Ca,xt=g(()=>{"use strict";l();Ca={}});var Qv,Dh=g(()=>{"use strict";l();xt();Qv={symbols:`
159
+ `,u=`${i}();`;return{newFunction:m,replacementCall:u}}async getCallHierarchy(e,t,o){try{let n=this.parseCode(e.content),s=e.filePath,i=null,a="",l=0,p=0;if(Ie(n,{Function(h){let T=h.node.loc;T&&T.start.line<=t&&T.end&&T.end.line>=t&&(i=h,l=T.start.line,p=T.start.column,h.node.type==="FunctionDeclaration"&&h.node.id?a=h.node.id.name:h.parent.type==="VariableDeclarator"&&h.parent.id.type==="Identifier"?a=h.parent.id.name:h.parent.type==="ClassMethod"||h.parent.type==="ObjectMethod"?h.parent.key.type==="Identifier"&&(a=h.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let d=[],m=[];Ie(n,{CallExpression(h){let T=h.node.loc;if(!T||T.start.line<l||T.end&&T.end.line>l+1e3)return;let C=!1,S=h;for(;S;){if(S.isFunction()&&S.node.type==="FunctionDeclaration"&&S.node.id?.name===a){C=!0;break}S=S.parentPath}if(!C)return;let w=h.node.callee,v="<unknown>";w.type==="Identifier"?v=w.name:w.type==="MemberExpression"&&w.property.type==="Identifier"&&(v=w.property.name),v!=="<unknown>"&&m.push({file:s,name:v,line:h.node.loc?.start.line||0,column:h.node.loc?.start.column||0})}}),Ie(n,{CallExpression(h){let T=h.node.callee,C=!1;if((T.type==="Identifier"&&T.name===a||T.type==="MemberExpression"&&T.property.type==="Identifier"&&T.property.name===a)&&(C=!0),C){let S="<global>",w=h;for(;w;){if(w.isFunction()){w.node.type==="FunctionDeclaration"&&w.node.id?S=w.node.id.name:w.parent.type==="VariableDeclarator"&&w.parent.id.type==="Identifier"?S=w.parent.id.name:(w.parent.type==="ClassMethod"||w.parent.type==="ObjectMethod")&&w.parent.key.type==="Identifier"&&(S=w.parent.key.name);break}w=w.parentPath}d.push({file:s,name:S,line:h.node.loc?.start.line||0,column:h.node.loc?.start.column||0})}}});let u=[...new Map(d.map(h=>[`${h.name}:${h.line}`,h])).values()],b=[...new Map(m.map(h=>[`${h.name}:${h.line}`,h])).values()];return{file:s,name:a,line:l,column:p,callers:u,callees:b}}catch{return null}}}});function $e(r,e){_a[r]=e}var _a,Ct=g(()=>{"use strict";c();_a={}});var eC,Nh=g(()=>{"use strict";c();Ct();eC={symbols:`
160
160
  (function_definition
161
161
  name: (identifier) @name.function) @definition.function
162
162
 
@@ -174,7 +174,7 @@ ${d}
174
174
  name: (dotted_name) @name) @import
175
175
  `,references:`
176
176
  (identifier) @reference
177
- `};Re("python",Qv)});var Xv,Ah=g(()=>{"use strict";l();xt();Xv={symbols:`
177
+ `};$e("python",eC)});var tC,Oh=g(()=>{"use strict";c();Ct();tC={symbols:`
178
178
  (function_declaration
179
179
  name: (identifier) @name.function) @definition.function
180
180
 
@@ -202,7 +202,7 @@ ${d}
202
202
  (identifier) @reference
203
203
  (field_identifier) @reference
204
204
  (type_identifier) @reference
205
- `};Re("go",Xv)});var Yv,Mh=g(()=>{"use strict";l();xt();Yv={symbols:`
205
+ `};$e("go",tC)});var oC,Ih=g(()=>{"use strict";c();Ct();oC={symbols:`
206
206
  (function_item
207
207
  name: (identifier) @name.function) @definition.function
208
208
 
@@ -224,7 +224,7 @@ ${d}
224
224
  (identifier) @reference
225
225
  (type_identifier) @reference
226
226
  (field_identifier) @reference
227
- `};Re("rust",Yv)});var Zv,Nh=g(()=>{"use strict";l();xt();Zv={symbols:`
227
+ `};$e("rust",oC)});var nC,Lh=g(()=>{"use strict";c();Ct();nC={symbols:`
228
228
  (method_declaration
229
229
  name: (identifier) @name.method) @definition.method
230
230
 
@@ -245,7 +245,7 @@ ${d}
245
245
  `,references:`
246
246
  (identifier) @reference
247
247
  (type_identifier) @reference
248
- `};Re("java",Zv)});var Oh,Ih=g(()=>{"use strict";l();xt();Oh={symbols:`
248
+ `};$e("java",nC)});var jh,Fh=g(()=>{"use strict";c();Ct();jh={symbols:`
249
249
  (function_definition
250
250
  declarator: (function_declarator
251
251
  declarator: (identifier) @name.function)) @definition.function
@@ -266,48 +266,48 @@ ${d}
266
266
  (identifier) @reference
267
267
  (type_identifier) @reference
268
268
  (field_identifier) @reference
269
- `};Re("cpp",Oh);Re("c",Oh)});var Qr,jh=g(()=>{"use strict";l();xt();Dh();Ah();Mh();Nh();Ih();Qr=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=Ca[n];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${n}`);let a=i[t],c=s.query(a);return{tree:o,captures:c.captures(o.rootNode)}}async findSymbols(e,t,o){return(await this.getSymbols(e,o)).filter(s=>s.name===t).map(s=>({file:e.filePath,line:s.line,column:s.column,kind:s.kind,name:s.name}))}async getSymbols(e,t){let{captures:o}=await this.executeQuery(e,"symbols"),n=[];for(let s of o)if(s.name.startsWith("name.")){let i=s.name.split(".")[1];(!t||t===i)&&n.push({name:s.node.text,kind:i,line:s.node.startPosition.row+1,column:s.node.startPosition.column})}return n}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),o=t.filter(s=>s.name==="import").map(s=>s.node),n=[];for(let s of o)n.push({source:s.text,imports:[s.text],line:s.startPosition.row+1,type:"side-effect"});return n}async findReferences(e,t,o){let{captures:n}=await this.executeQuery(e,"references"),s=e.content.split(`
270
- `),i=[];for(let a of n)if(a.node.text===t){let c=a.node.parent?.type.includes("definition")||a.node.parent?.type.includes("declaration");if(!c||o){let p=a.node.startPosition.row+1;i.push({file:e.filePath,line:p,column:a.node.startPosition.column,context:s[p-1].trim(),isDeclaration:!!c})}}return i}async getSymbolAtPosition(e,t,o){let{tree:n}=await this.context.getTree(e.filePath,e.content),s=n.rootNode.descendantForPosition({row:t-1,column:o});return s&&s.type==="identifier"?s.text:null}async getDefinition(e,t){let o=await this.findSymbols(e,t);return o.length>0?o[0]:null}async getDiagnostics(e){let{tree:t}=await this.context.getTree(e.filePath,e.content),o=[];function n(s){if(s.hasError()){s.type==="ERROR"&&o.push({message:`Syntax error at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"});for(let i of s.children)n(i)}else s.isMissing&&s.isMissing()&&o.push({message:`Missing ${s.type} at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"})}return n(t.rootNode),o}async getExports(e){return[]}async getOutline(e){return(await this.getSymbols(e)).map(o=>({name:o.name,kind:o.kind,line:o.line,column:o.column,children:[]}))}async extractFunction(e,t,o,n,s,i){let a=e.content.split(`
271
- `),c=Math.max(0,t-1),p=Math.min(a.length,n),d=a.slice(c,p).join(`
272
- `),m="",f="",b=e.filePath.split(".").pop()?.toLowerCase();return b==="py"||b==="pyi"?(m=`
269
+ `};$e("cpp",jh);$e("c",jh)});var Zr,qh=g(()=>{"use strict";c();Ct();Nh();Oh();Ih();Lh();Fh();Zr=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=_a[n];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${n}`);let a=i[t],l=s.query(a);return{tree:o,captures:l.captures(o.rootNode)}}async findSymbols(e,t,o){return(await this.getSymbols(e,o)).filter(s=>s.name===t).map(s=>({file:e.filePath,line:s.line,column:s.column,kind:s.kind,name:s.name}))}async getSymbols(e,t){let{captures:o}=await this.executeQuery(e,"symbols"),n=[];for(let s of o)if(s.name.startsWith("name.")){let i=s.name.split(".")[1];(!t||t===i)&&n.push({name:s.node.text,kind:i,line:s.node.startPosition.row+1,column:s.node.startPosition.column})}return n}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),o=t.filter(s=>s.name==="import").map(s=>s.node),n=[];for(let s of o)n.push({source:s.text,imports:[s.text],line:s.startPosition.row+1,type:"side-effect"});return n}async findReferences(e,t,o){let{captures:n}=await this.executeQuery(e,"references"),s=e.content.split(`
270
+ `),i=[];for(let a of n)if(a.node.text===t){let l=a.node.parent?.type.includes("definition")||a.node.parent?.type.includes("declaration");if(!l||o){let p=a.node.startPosition.row+1;i.push({file:e.filePath,line:p,column:a.node.startPosition.column,context:s[p-1].trim(),isDeclaration:!!l})}}return i}async getSymbolAtPosition(e,t,o){let{tree:n}=await this.context.getTree(e.filePath,e.content),s=n.rootNode.descendantForPosition({row:t-1,column:o});return s&&s.type==="identifier"?s.text:null}async getDefinition(e,t){let o=await this.findSymbols(e,t);return o.length>0?o[0]:null}async getDiagnostics(e){let{tree:t}=await this.context.getTree(e.filePath,e.content),o=[];function n(s){if(s.hasError()){s.type==="ERROR"&&o.push({message:`Syntax error at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"});for(let i of s.children)n(i)}else s.isMissing&&s.isMissing()&&o.push({message:`Missing ${s.type} at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"})}return n(t.rootNode),o}async getExports(e){return[]}async getOutline(e){return(await this.getSymbols(e)).map(o=>({name:o.name,kind:o.kind,line:o.line,column:o.column,children:[]}))}async extractFunction(e,t,o,n,s,i){let a=e.content.split(`
271
+ `),l=Math.max(0,t-1),p=Math.min(a.length,n),d=a.slice(l,p).join(`
272
+ `),m="",u="",b=e.filePath.split(".").pop()?.toLowerCase();return b==="py"||b==="pyi"?(m=`
273
273
  def ${i}():
274
274
  ${d.split(`
275
275
  `).map(h=>" "+h).join(`
276
276
  `)}
277
- `,f=`${i}()`):b==="go"?(m=`
277
+ `,u=`${i}()`):b==="go"?(m=`
278
278
  func ${i}() {
279
279
  ${d}
280
280
  }
281
- `,f=`${i}()`):b==="rs"?(m=`
281
+ `,u=`${i}()`):b==="rs"?(m=`
282
282
  fn ${i}() {
283
283
  ${d}
284
284
  }
285
- `,f=`${i}();`):b==="sh"||b==="bash"?(m=`
285
+ `,u=`${i}();`):b==="sh"||b==="bash"?(m=`
286
286
  ${i}() {
287
287
  ${d}
288
288
  }
289
- `,f=`${i}`):(m=`
289
+ `,u=`${i}`):(m=`
290
290
  void ${i}() {
291
291
  ${d}
292
292
  }
293
- `,f=`${i}();`),{newFunction:m,replacementCall:f}}async getCallHierarchy(e,t,o){let n=await this.getSymbolAtPosition(e,t,o);if(!n)return null;let i=(await this.findReferences(e,n,!1)).map(a=>({file:a.file,name:a.context.trim()||"<anonymous>",line:a.line,column:a.column}));return{file:e.filePath,name:n,line:t,column:o,callers:i,callees:[]}}}});var Xr,Lh=g(()=>{"use strict";l();wa();Eh();jh();Xr=class{constructor(e){this.context=e;this.babelParser=new Vr,this.treeSitterParser=new Qr(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Hr(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});var Bo,Zr,Yr,Fh=g(()=>{"use strict";l();Bo=require("fs"),Zr=require("path");ve();Yr=class{isBuilt=!1;isBuilding=!1;data={symbolLocations:new Map};fileMtimes=new Map;supportedExtensions=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];async getAllSupportedFiles(e){let t=[];try{let o=(0,Bo.readdirSync)(e,{withFileTypes:!0});for(let n of o){let s=(0,Zr.join)(e,n.name);n.name==="node_modules"||n.name===".git"||n.name==="dist"||n.name==="build"||(n.isDirectory()?t.push(...await this.getAllSupportedFiles(s)):n.isFile()&&this.supportedExtensions.includes((0,Zr.extname)(n.name).toLowerCase())&&t.push(s))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let o of t)await this.updateFile(o);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let o=(0,Bo.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=(0,Bo.readFileSync)(e,"utf-8"),s=W.getParser(e);this.removeFileFromIndex(e);let i=await s.getSymbols({filePath:e,content:n});for(let a of i){let c=this.data.symbolLocations.get(a.name);c?c.add(e):this.data.symbolLocations.set(a.name,new Set([e]))}this.fileMtimes.set(e,o)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,o]of this.data.symbolLocations.entries())o.delete(e),o.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let o=this.data.symbolLocations.get(e);return o?Array.from(o):[]}}});var eC,W,zo,ve=g(()=>{"use strict";l();Rh();Lh();Fh();eC=new Jr,W=new Xr(eC),zo=new Yr});async function qh(r,e,t){try{let o=(0,Ho.readFileSync)(r,"utf-8");return await W.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function Wh(r,e,t){let o=[];try{let n=(0,Ho.readdirSync)(r,{withFileTypes:!0});for(let s of n){let i=(0,es.join)(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await Wh(i,e,t);o.push(...a)}else if(s.isFile()&&tC.includes((0,es.extname)(s.name))){let a=await qh(i,e,t);o.push(...a)}}}}catch{}return o}async function oC(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=(0,Ho.statSync)(t),s;if(n.isDirectory())s=await Wh(t,e,o);else if(n.isFile())s=await qh(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 Ho,es,tC,Ko,ka=g(()=>{"use strict";l();Ho=require("fs"),es=require("path");xh();ve();_();tC=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Ko={name:hh,displayName:yh,description:bh,parameters:wh,category:Th,execute:oC}});var Uh,Gh,Bh,zh,Hh,Kh=g(()=>{"use strict";l();Uh="coding.get_symbols",Gh="Get Symbols",Bh="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",zh="coding",Hh={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});async function nC(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=(0,Jh.readFileSync)(e,"utf-8"),s=await W.getParser(e).getSymbols({filePath:e,content:o},t);return JSON.stringify({file:e,count:s.length,symbols:s},null,2)}catch(o){throw new Error(`Failed to parse file "${e}": ${o.message}`)}}var Jh,Jo,Sa=g(()=>{"use strict";l();Jh=require("fs");Kh();ve();_();Jo={name:Uh,displayName:Gh,description:Bh,parameters:Hh,category:zh,execute:nC}});var Vh,Qh,Xh,Yh,Zh,ey=g(()=>{"use strict";l();Vh="coding.get_imports",Qh="Get Imports",Xh="List all import statements in a JavaScript/TypeScript file",Yh="coding",Zh={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function rC(r){let e=r.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,ty.readFileSync)(e,"utf-8"),n=await W.getParser(e).getImports({filePath:e,content:t});return JSON.stringify({file:e,count:n.length,imports:n},null,2)}catch(t){throw new Error(`Failed to map explicit imports in file "${e}": ${t.message}`)}}var ty,Vo,_a=g(()=>{"use strict";l();ty=require("fs");ey();ve();_();Vo={name:Vh,displayName:Qh,description:Xh,parameters:Zh,category:Yh,execute:rC}});var oy,ny,ry,sy,iy,ay=g(()=>{"use strict";l();oy="coding.find_references",ny="Find References",ry="Find all references to a symbol across JavaScript/TypeScript files",sy="coding",iy={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});async function ly(r,e,t){try{let o=(0,ts.readFileSync)(r,"utf-8");return await W.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function sC(r,e,t){let o=[];await zo.buildIndex(r);let n=await zo.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await ly(s,e,t);o.push(...i)}return o}async function iC(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=(0,ts.statSync)(t),s;if(n.isDirectory())s=await sC(t,e,o);else if(n.isFile())s=await ly(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 ts,Qo,Pa=g(()=>{"use strict";l();ts=require("fs");ay();ve();_();Qo={name:oy,displayName:ny,description:ry,parameters:iy,category:sy,execute:iC}});var cy,py,my,dy,uy,fy=g(()=>{"use strict";l();cy="coding.go_to_definition",py="Go To Definition",my="Jump to the definition of a symbol at a specific location in a file",dy="coding",uy={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});async function aC(r,e,t){try{let o=(0,Ln.readFileSync)(r,"utf-8");return await W.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function hy(r,e){try{let t=(0,Ln.readFileSync)(r,"utf-8");return await W.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function lC(r,e){await zo.buildIndex(r);let t=await zo.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await hy(o,e);if(n)return n}return null}async function cC(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 aC(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await hy(e,s);if(!i){let a=n||(0,gy.dirname)(e);(0,Ln.statSync)(a).isDirectory()&&(i=await lC(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 Ln,gy,Xo,Ra=g(()=>{"use strict";l();Ln=require("fs"),gy=require("path");fy();ve();Xo={name:cy,displayName:py,description:my,parameters:uy,category:dy,execute:cC}});var yy,by,Ty,wy,xy,vy=g(()=>{"use strict";l();yy="coding.multi_file_edit",by="Multi-File Edit",Ty="Edit multiple files atomically with rollback on failure",wy="coding",xy={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});async function pC(r){let e=r.edits,t=r.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let s of e){if(!s.file)throw new Error("Each edit must have a file property");if(!s.changes||!Array.isArray(s.changes))throw new Error("Each edit must have a changes array");if(!(0,vt.existsSync)(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=(0,vt.readFileSync)(s.file,"utf-8");t&&o.push({file:s.file,content:i});let a=i;for(let c of s.changes){if(!c.oldText)throw new Error("Each change must have oldText property");if(c.newText===void 0)throw new Error("Each change must have newText property");let p=(a.match(new RegExp(mC(c.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${s.file}: "${c.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${s.file}: "${c.oldText.substring(0,50)}..." appears ${p} times`);a=a.replace(c.oldText,c.newText)}(0,vt.writeFileSync)(s.file,a,"utf-8"),n.push(s.file)}return JSON.stringify({success:!0,filesModified:n.length,files:n},null,2)}catch(s){if(t&&o.length>0){for(let i of o)try{(0,vt.writeFileSync)(i.file,i.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${s.message}`)}throw new Error(`Multi-file edit failed: ${s.message}`)}}function mC(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var vt,Yo,$a=g(()=>{"use strict";l();vt=require("fs");vy();Yo={name:yy,displayName:by,description:Ty,parameters:xy,category:wy,execute:pC,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var Cy,ky,Sy,_y,Py,Ry=g(()=>{"use strict";l();Cy="coding.refactor_rename",ky="Refactor Rename",Sy="Rename a symbol across the entire codebase intelligently",_y="coding",Py={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});function fC(r,e,t,o){let n=[];try{let s=(0,Zo.readFileSync)(r,"utf-8"),i=s.split(`
294
- `),a=(0,$y.parse)(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),c=[];if(dC(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 f=p[m],b=f.substring(0,d.column),h=f.substring(d.column+d.length);p[m]=b+t+h}}(0,Zo.writeFileSync)(r,p.join(`
295
- `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function Ey(r,e,t,o){let n=[];try{let s=(0,Zo.readdirSync)(r,{withFileTypes:!0});for(let i of s){let a=(0,os.join)(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...Ey(a,e,t,o));else if(i.isFile()&&uC.includes((0,os.extname)(i.name))){let c=fC(a,e,t,o);c.occurrences>0&&n.push(c)}}}}catch{}return n}async function gC(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=Ey(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 Zo,os,$y,Ea,dC,uC,en,Da=g(()=>{"use strict";l();Zo=require("fs"),os=require("path"),$y=require("@babel/parser"),Ea=x(require("@babel/traverse"),1);Ry();dC=Ea.default||Ea,uC=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];en={name:Cy,displayName:ky,description:Sy,parameters:Py,category:_y,execute:gC,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var Dy,Ay,My,Ny,Oy,Iy=g(()=>{"use strict";l();Dy="coding.get_outline",Ay="Get File Outline",My="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",Ny="coding",Oy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function hC(r){let e=r.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,ns.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,ns.readFileSync)(e,"utf-8"),o=W.getParser(e);if(!o.getOutline)return JSON.stringify({file:e,error:"Outline extraction is not specifically implemented for this language yet."});let n=await o.getOutline({filePath:e,content:t});return JSON.stringify({file:e,outline:n},null,2)}catch(t){throw new Error(`Failed to safely extract outline from file "${e}": ${t.message}`)}}var ns,tn,Aa=g(()=>{"use strict";l();ns=require("fs");Iy();ve();_();tn={name:Dy,displayName:Ay,description:My,parameters:Oy,category:Ny,execute:hC}});var jy,Ly,Fy,qy,Wy,Uy=g(()=>{"use strict";l();jy="coding.get_diagnostics",Ly="Get File Diagnostics",Fy="Gets syntax errors and warnings for a file utilizing AST parsing.",qy="coding",Wy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function yC(r){let e=r.file;if(!e)throw new Error("file is required");try{if(!(0,rs.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,rs.readFileSync)(e,"utf-8"),o=W.getParser(e);if(!o.getDiagnostics)return JSON.stringify({file:e,error:"Diagnostics extraction is not specifically implemented for this language yet."});let n=await o.getDiagnostics({filePath:e,content:t});return JSON.stringify({file:e,diagnostics:n},null,2)}catch(t){throw new Error(`Failed to get diagnostics from file "${e}": ${t.message}`)}}var rs,on,Ma=g(()=>{"use strict";l();rs=require("fs");Uy();ve();on={name:jy,displayName:Ly,description:Fy,parameters:Wy,category:qy,execute:yC}});var Gy,By,zy,Hy,Ky,Jy=g(()=>{"use strict";l();Gy="coding.get_exports",By="Get File Exports",zy="Lists all symbols exported by a file.",Hy="coding",Ky={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function bC(r){let e=r.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,ss.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,ss.readFileSync)(e,"utf-8"),o=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 ss,nn,Na=g(()=>{"use strict";l();ss=require("fs");Jy();ve();_();nn={name:Gy,displayName:By,description:zy,parameters:Ky,category:Hy,execute:bC}});var Vy,Qy,Xy,Yy,Zy,eb=g(()=>{"use strict";l();Vy="coding.extract_function",Qy="Extract Function",Xy="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Yy="coding",Zy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});async function TC(r){let e=r.file,t=r.startLine,o=r.startColumn,n=r.endLine,s=r.endColumn,i=r.newFunctionName;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("startLine is required");if(o===void 0)throw new Error("startColumn is required");if(n===void 0)throw new Error("endLine is required");if(s===void 0)throw new Error("endColumn is required");if(!i)throw new Error("newFunctionName is required");try{if(!(0,is.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=(0,is.readFileSync)(e,"utf-8"),c=W.getParser(e);if(!c.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await c.extractFunction({filePath:e,content:a},t,o,n,s,i);return JSON.stringify({file:e,result:p},null,2)}catch(a){throw new Error(`Failed to extract function from file "${e}": ${a.message}`)}}var is,rn,Oa=g(()=>{"use strict";l();is=require("fs");eb();ve();rn={name:Vy,displayName:Qy,description:Xy,parameters:Zy,category:Yy,execute:TC}});var tb,ob,nb,rb,sb,ib=g(()=>{"use strict";l();tb="coding.get_call_hierarchy",ob="Get Call Hierarchy",nb="Shows callers and callees of a specific function or method.",rb="coding",sb={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});async function wC(r){let e=r.file,t=r.line,o=r.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");try{if(!(0,as.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=(0,as.readFileSync)(e,"utf-8"),s=W.getParser(e);if(!s.getCallHierarchy)return JSON.stringify({file:e,error:"Call hierarchy is not specifically implemented for this language yet."});let i=await s.getCallHierarchy({filePath:e,content:n},t,o);return JSON.stringify({file:e,hierarchy:i},null,2)}catch(n){throw new Error(`Failed to get call hierarchy from file "${e}": ${n.message}`)}}var as,sn,Ia=g(()=>{"use strict";l();as=require("fs");ib();ve();sn={name:tb,displayName:ob,description:nb,parameters:sb,category:rb,execute:wC}});var ab={};ee(ab,{codingExtractFunctionTool:()=>rn,codingFindReferencesTool:()=>Qo,codingFindSymbolTool:()=>Ko,codingGetCallHierarchyTool:()=>sn,codingGetDiagnosticsTool:()=>on,codingGetExportsTool:()=>nn,codingGetImportsTool:()=>Vo,codingGetOutlineTool:()=>tn,codingGetSymbolsTool:()=>Jo,codingGoToDefinitionTool:()=>Xo,codingMultiFileEditTool:()=>Yo,codingRefactorRenameTool:()=>en,codingToolsProject:()=>ja});var ja,La=g(()=>{"use strict";l();ka();Sa();_a();Pa();Ra();$a();Da();Aa();Ma();Na();Oa();Ia();ka();Sa();_a();Pa();Ra();$a();Da();Aa();Ma();Na();Oa();Ia();ja={manifest:{key:"coding",name:"coding-tools",displayName:"Code Intelligence",version:"1.0.0",description:"AST-aware code intelligence tools for finding symbols, references, and analyzing code structure.",author:"Sajeer",tools:["coding.find_symbol","coding.get_symbols","coding.get_imports","coding.find_references","coding.go_to_definition","coding.get_outline","coding.get_diagnostics","coding.get_exports","coding.extract_function","coding.get_call_hierarchy","coding.multi_file_edit","coding.refactor_rename"],category:"coding"},tools:[Ko,Jo,Vo,Qo,Xo,tn,on,nn,rn,sn,Yo,en],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var lb,cb=g(()=>{"use strict";l();lb={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function G(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,pb.simpleGit)(e)}var pb,$e=g(()=>{"use strict";l();pb=require("simple-git")});var Fn,mb=g(()=>{"use strict";l();cb();$e();Fn={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:lb,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 db,ub=g(()=>{"use strict";l();db={type:"object",properties:{path:{type:"string",description:"Optional path to get the diff for. If omitted, gets the diff for the entire repository."},base:{type:"string",description:"Optional base commit/ref for comparing two revisions. When used with head, runs git diff base...head."},head:{type:"string",description:"Optional head commit/ref for comparing two revisions. When used with base, runs git diff base...head."},staged:{type:"boolean",description:"If true, gets the diff of staged changes instead of unstaged changes.",default:!1},cloneDir:{type:"string",description:"Optional local repository directory, typically the cloneDir returned by git.clone. When provided, this tool runs in that repository instead of the current working directory."}}}});var qn,fb=g(()=>{"use strict";l();ub();$e();qn={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:db,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 gb,hb=g(()=>{"use strict";l();gb={type:"object",properties:{maxCount:{type:"number",description:"Maximum number of commits to return. Defaults to 10 to prevent large outputs.",default:10},path:{type:"string",description:"Optional path to get the log for specific file or directory."},cloneDir:{type:"string",description:"Optional local repository directory, typically the cloneDir returned by git.clone. When provided, this tool runs in that repository instead of the current working directory."}}}});var Wn,yb=g(()=>{"use strict";l();hb();$e();Wn={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:gb,execute:async r=>{let e=r.maxCount||10,t=r.path,o=r.cloneDir;try{let n=G(o),s={maxCount:e};t&&(s.file=t);let i=await n.log(s);return i.all.length===0?"No commits found.":i.all.map(a=>`Commit: ${a.hash}
293
+ `,u=`${i}();`),{newFunction:m,replacementCall:u}}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 es,Wh=g(()=>{"use strict";c();Ca();Mh();qh();es=class{constructor(e){this.context=e;this.babelParser=new Yr,this.treeSitterParser=new Zr(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(Vr(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});var Ho,os,ts,Uh=g(()=>{"use strict";c();Ho=require("fs"),os=require("path");Ce();ts=class{isBuilt=!1;isBuilding=!1;data={symbolLocations:new Map};fileMtimes=new Map;supportedExtensions=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];async getAllSupportedFiles(e){let t=[];try{let o=(0,Ho.readdirSync)(e,{withFileTypes:!0});for(let n of o){let s=(0,os.join)(e,n.name);n.name==="node_modules"||n.name===".git"||n.name==="dist"||n.name==="build"||(n.isDirectory()?t.push(...await this.getAllSupportedFiles(s)):n.isFile()&&this.supportedExtensions.includes((0,os.extname)(n.name).toLowerCase())&&t.push(s))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let o of t)await this.updateFile(o);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let o=(0,Ho.statSync)(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let n=(0,Ho.readFileSync)(e,"utf-8"),s=U.getParser(e);this.removeFileFromIndex(e);let i=await s.getSymbols({filePath:e,content:n});for(let a of i){let l=this.data.symbolLocations.get(a.name);l?l.add(e):this.data.symbolLocations.set(a.name,new Set([e]))}this.fileMtimes.set(e,o)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,o]of this.data.symbolLocations.entries())o.delete(e),o.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let o=this.data.symbolLocations.get(e);return o?Array.from(o):[]}}});var rC,U,Ko,Ce=g(()=>{"use strict";c();Dh();Wh();Uh();rC=new Xr,U=new es(rC),Ko=new ts});async function Gh(r,e,t){try{let o=(0,Jo.readFileSync)(r,"utf-8");return await U.getParser(r).findSymbols({filePath:r,content:o},e,t)}catch{return[]}}async function Bh(r,e,t){let o=[];try{let n=(0,Jo.readdirSync)(r,{withFileTypes:!0});for(let s of n){let i=(0,ns.join)(r,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await Bh(i,e,t);o.push(...a)}else if(s.isFile()&&sC.includes((0,ns.extname)(s.name))){let a=await Gh(i,e,t);o.push(...a)}}}}catch{}return o}async function iC(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=(0,Jo.statSync)(t),s;if(n.isDirectory())s=await Bh(t,e,o);else if(n.isFile())s=await Gh(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 Jo,ns,sC,Vo,Pa=g(()=>{"use strict";c();Jo=require("fs"),ns=require("path");kh();Ce();P();sC=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];Vo={name:Th,displayName:wh,description:xh,parameters:Ch,category:vh,execute:iC}});var zh,Hh,Kh,Jh,Vh,Qh=g(()=>{"use strict";c();zh="coding.get_symbols",Hh="Get Symbols",Kh="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Jh="coding",Vh={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});async function aC(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=(0,Xh.readFileSync)(e,"utf-8"),s=await U.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 Xh,Qo,Ra=g(()=>{"use strict";c();Xh=require("fs");Qh();Ce();P();Qo={name:zh,displayName:Hh,description:Kh,parameters:Vh,category:Jh,execute:aC}});var Yh,Zh,ey,ty,oy,ny=g(()=>{"use strict";c();Yh="coding.get_imports",Zh="Get Imports",ey="List all import statements in a JavaScript/TypeScript file",ty="coding",oy={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});async function lC(r){let e=r.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=(0,ry.readFileSync)(e,"utf-8"),n=await U.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 ry,Xo,$a=g(()=>{"use strict";c();ry=require("fs");ny();Ce();P();Xo={name:Yh,displayName:Zh,description:ey,parameters:oy,category:ty,execute:lC}});var sy,iy,ay,ly,cy,py=g(()=>{"use strict";c();sy="coding.find_references",iy="Find References",ay="Find all references to a symbol across JavaScript/TypeScript files",ly="coding",cy={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});async function my(r,e,t){try{let o=(0,rs.readFileSync)(r,"utf-8");return await U.getParser(r).findReferences({filePath:r,content:o},e,t)}catch{return[]}}async function cC(r,e,t){let o=[];await Ko.buildIndex(r);let n=await Ko.getDefinitionFiles(e,r);for(let s of n)if(s.startsWith(r)){let i=await my(s,e,t);o.push(...i)}return o}async function pC(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=(0,rs.statSync)(t),s;if(n.isDirectory())s=await cC(t,e,o);else if(n.isFile())s=await my(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 rs,Yo,Ea=g(()=>{"use strict";c();rs=require("fs");py();Ce();P();Yo={name:sy,displayName:iy,description:ay,parameters:cy,category:ly,execute:pC}});var dy,uy,fy,gy,hy,yy=g(()=>{"use strict";c();dy="coding.go_to_definition",uy="Go To Definition",fy="Jump to the definition of a symbol at a specific location in a file",gy="coding",hy={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});async function mC(r,e,t){try{let o=(0,Wn.readFileSync)(r,"utf-8");return await U.getParser(r).getSymbolAtPosition({filePath:r,content:o},e,t)}catch{return null}}async function Ty(r,e){try{let t=(0,Wn.readFileSync)(r,"utf-8");return await U.getParser(r).getDefinition({filePath:r,content:t},e)}catch{return null}}async function dC(r,e){await Ko.buildIndex(r);let t=await Ko.getDefinitionFiles(e,r);for(let o of t)if(o.startsWith(r)){let n=await Ty(o,e);if(n)return n}return null}async function uC(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 mC(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await Ty(e,s);if(!i){let a=n||(0,by.dirname)(e);(0,Wn.statSync)(a).isDirectory()&&(i=await dC(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 Wn,by,Zo,Da=g(()=>{"use strict";c();Wn=require("fs"),by=require("path");yy();Ce();Zo={name:dy,displayName:uy,description:fy,parameters:hy,category:gy,execute:uC}});var wy,xy,vy,Cy,ky,Sy=g(()=>{"use strict";c();wy="coding.multi_file_edit",xy="Multi-File Edit",vy="Edit multiple files atomically with rollback on failure",Cy="coding",ky={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});async function fC(r){let e=r.edits,t=r.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let s of e){if(!s.file)throw new Error("Each edit must have a file property");if(!s.changes||!Array.isArray(s.changes))throw new Error("Each edit must have a changes array");if(!(0,kt.existsSync)(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],n=[];try{for(let s of e){let i=(0,kt.readFileSync)(s.file,"utf-8");t&&o.push({file:s.file,content:i});let a=i;for(let l of s.changes){if(!l.oldText)throw new Error("Each change must have oldText property");if(l.newText===void 0)throw new Error("Each change must have newText property");let p=(a.match(new RegExp(gC(l.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${s.file}: "${l.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${s.file}: "${l.oldText.substring(0,50)}..." appears ${p} times`);a=a.replace(l.oldText,l.newText)}(0,kt.writeFileSync)(s.file,a,"utf-8"),n.push(s.file)}return JSON.stringify({success:!0,filesModified:n.length,files:n},null,2)}catch(s){if(t&&o.length>0){for(let i of o)try{(0,kt.writeFileSync)(i.file,i.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${s.message}`)}throw new Error(`Multi-file edit failed: ${s.message}`)}}function gC(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var kt,en,Aa=g(()=>{"use strict";c();kt=require("fs");Sy();en={name:wy,displayName:xy,description:vy,parameters:ky,category:Cy,execute:fC,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var _y,Py,Ry,$y,Ey,Dy=g(()=>{"use strict";c();_y="coding.refactor_rename",Py="Refactor Rename",Ry="Rename a symbol across the entire codebase intelligently",$y="coding",Ey={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});function bC(r,e,t,o){let n=[];try{let s=(0,tn.readFileSync)(r,"utf-8"),i=s.split(`
294
+ `),a=(0,Ay.parse)(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),l=[];if(hC(a,{Identifier(p){if(p.node.name===e){let d=p.node.loc?.start.line||0,m=p.node.loc?.start.column||0;l.push({line:d,column:m,length:e.length}),n.push({file:r,line:d,column:m,oldName:e,newName:t})}}}),!o&&l.length>0){l.sort((d,m)=>d.line!==m.line?m.line-d.line:m.column-d.column);let p=[...i];for(let d of l){let m=d.line-1;if(m>=0&&m<p.length){let u=p[m],b=u.substring(0,d.column),h=u.substring(d.column+d.length);p[m]=b+t+h}}(0,tn.writeFileSync)(r,p.join(`
295
+ `),"utf-8")}}catch{}return{file:r,occurrences:n.length,changes:n}}function My(r,e,t,o){let n=[];try{let s=(0,tn.readdirSync)(r,{withFileTypes:!0});for(let i of s){let a=(0,ss.join)(r,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())n.push(...My(a,e,t,o));else if(i.isFile()&&yC.includes((0,ss.extname)(i.name))){let l=bC(a,e,t,o);l.occurrences>0&&n.push(l)}}}}catch{}return n}async function TC(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=My(o,e,t,n),i=s.reduce((l,p)=>l+p.occurrences,0),a=s.length;return JSON.stringify({success:!0,dryRun:n,oldName:e,newName:t,filesAffected:a,totalOccurrences:i,changes:s},null,2)}var tn,ss,Ay,Ma,hC,yC,on,Na=g(()=>{"use strict";c();tn=require("fs"),ss=require("path"),Ay=require("@babel/parser"),Ma=x(require("@babel/traverse"),1);Dy();hC=Ma.default||Ma,yC=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];on={name:_y,displayName:Py,description:Ry,parameters:Ey,category:$y,execute:TC,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var Ny,Oy,Iy,Ly,jy,Fy=g(()=>{"use strict";c();Ny="coding.get_outline",Oy="Get File Outline",Iy="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",Ly="coding",jy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});async function wC(r){let e=r.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,is.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,is.readFileSync)(e,"utf-8"),o=U.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 is,nn,Oa=g(()=>{"use strict";c();is=require("fs");Fy();Ce();P();nn={name:Ny,displayName:Oy,description:Iy,parameters:jy,category:Ly,execute:wC}});var qy,Wy,Uy,Gy,By,zy=g(()=>{"use strict";c();qy="coding.get_diagnostics",Wy="Get File Diagnostics",Uy="Gets syntax errors and warnings for a file utilizing AST parsing.",Gy="coding",By={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});async function xC(r){let e=r.file;if(!e)throw new Error("file is required");try{if(!(0,as.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,as.readFileSync)(e,"utf-8"),o=U.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 as,rn,Ia=g(()=>{"use strict";c();as=require("fs");zy();Ce();rn={name:qy,displayName:Wy,description:Uy,parameters:By,category:Gy,execute:xC}});var Hy,Ky,Jy,Vy,Qy,Xy=g(()=>{"use strict";c();Hy="coding.get_exports",Ky="Get File Exports",Jy="Lists all symbols exported by a file.",Vy="coding",Qy={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});async function vC(r){let e=r.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!(0,ls.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=(0,ls.readFileSync)(e,"utf-8"),o=U.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 ls,sn,La=g(()=>{"use strict";c();ls=require("fs");Xy();Ce();P();sn={name:Hy,displayName:Ky,description:Jy,parameters:Qy,category:Vy,execute:vC}});var Yy,Zy,eb,tb,ob,nb=g(()=>{"use strict";c();Yy="coding.extract_function",Zy="Extract Function",eb="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",tb="coding",ob={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});async function CC(r){let e=r.file,t=r.startLine,o=r.startColumn,n=r.endLine,s=r.endColumn,i=r.newFunctionName;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("startLine is required");if(o===void 0)throw new Error("startColumn is required");if(n===void 0)throw new Error("endLine is required");if(s===void 0)throw new Error("endColumn is required");if(!i)throw new Error("newFunctionName is required");try{if(!(0,cs.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=(0,cs.readFileSync)(e,"utf-8"),l=U.getParser(e);if(!l.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await l.extractFunction({filePath:e,content:a},t,o,n,s,i);return JSON.stringify({file:e,result:p},null,2)}catch(a){throw new Error(`Failed to extract function from file "${e}": ${a.message}`)}}var cs,an,ja=g(()=>{"use strict";c();cs=require("fs");nb();Ce();an={name:Yy,displayName:Zy,description:eb,parameters:ob,category:tb,execute:CC}});var rb,sb,ib,ab,lb,cb=g(()=>{"use strict";c();rb="coding.get_call_hierarchy",sb="Get Call Hierarchy",ib="Shows callers and callees of a specific function or method.",ab="coding",lb={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});async function kC(r){let e=r.file,t=r.line,o=r.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");try{if(!(0,ps.statSync)(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let n=(0,ps.readFileSync)(e,"utf-8"),s=U.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 ps,ln,Fa=g(()=>{"use strict";c();ps=require("fs");cb();Ce();ln={name:rb,displayName:sb,description:ib,parameters:lb,category:ab,execute:kC}});var pb={};te(pb,{codingExtractFunctionTool:()=>an,codingFindReferencesTool:()=>Yo,codingFindSymbolTool:()=>Vo,codingGetCallHierarchyTool:()=>ln,codingGetDiagnosticsTool:()=>rn,codingGetExportsTool:()=>sn,codingGetImportsTool:()=>Xo,codingGetOutlineTool:()=>nn,codingGetSymbolsTool:()=>Qo,codingGoToDefinitionTool:()=>Zo,codingMultiFileEditTool:()=>en,codingRefactorRenameTool:()=>on,codingToolsProject:()=>qa});var qa,Wa=g(()=>{"use strict";c();Pa();Ra();$a();Ea();Da();Aa();Na();Oa();Ia();La();ja();Fa();Pa();Ra();$a();Ea();Da();Aa();Na();Oa();Ia();La();ja();Fa();qa={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,nn,rn,sn,an,ln,en,on],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var mb,db=g(()=>{"use strict";c();mb={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});function z(r){let e={baseDir:r||process.cwd(),binary:"git",maxConcurrentProcesses:6};return(0,ub.simpleGit)(e)}var ub,Ee=g(()=>{"use strict";c();ub=require("simple-git")});var Un,fb=g(()=>{"use strict";c();db();Ee();Un={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:mb,execute:async r=>{let e=r.path;try{let o=await z().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 gb,hb=g(()=>{"use strict";c();gb={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 Gn,yb=g(()=>{"use strict";c();hb();Ee();Gn={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:gb,execute:async r=>{let e=r.path,t=r.base,o=r.head,n=r.staged,s=r.cloneDir;try{let i=z(s),a=[];if(t||o){if(!t||!o)return"Error getting git diff: both base and head are required when comparing revisions.";a.push(`${t}...${o}`)}n&&a.push("--cached"),e&&a.push("--",e);let l=await i.diff(a);return l||"No changes found."}catch(i){return`Error getting git diff: ${i instanceof Error?i.message:String(i)}`}}}});var bb,Tb=g(()=>{"use strict";c();bb={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 Bn,wb=g(()=>{"use strict";c();Tb();Ee();Bn={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:bb,execute:async r=>{let e=r.maxCount||10,t=r.path,o=r.cloneDir;try{let n=z(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 bb,Tb=g(()=>{"use strict";l();bb={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Un,wb=g(()=>{"use strict";l();Tb();$e();Un={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:bb,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 xb,vb=g(()=>{"use strict";l();xb={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Gn,Cb=g(()=>{"use strict";l();vb();$e();Gn={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:xb,execute:async r=>{let e=r.message;try{let o=await G().commit(e);return o.commit?`Successfully committed changes.
301
+ `)}catch(n){return`Error getting git log: ${n instanceof Error?n.message:String(n)}`}}}});var xb,vb=g(()=>{"use strict";c();xb={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var zn,Cb=g(()=>{"use strict";c();vb();Ee();zn={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:xb,execute:async r=>{let e=r.path;try{return await z().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var kb,Sb=g(()=>{"use strict";c();kb={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Hn,_b=g(()=>{"use strict";c();Sb();Ee();Hn={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:kb,execute:async r=>{let e=r.message;try{let o=await z().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 kb,Sb=g(()=>{"use strict";l();kb={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."},sha:{type:"string",description:"Optional commit SHA or ref to blame at. If omitted, blames the current checkout."},cloneDir:{type:"string",description:"Optional local repository directory, typically the cloneDir returned by git.clone. When provided, this tool runs in that repository instead of the current working directory."}},required:["path"]}});var Bn,_b=g(()=>{"use strict";l();Sb();$e();Bn={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:kb,execute:async r=>{let e=r.path,t=r.sha,o=r.cloneDir;try{let n=G(o),s=["blame"];return t&&s.push(t),s.push("--",e),await n.raw(s)}catch(n){return`Error running git blame: ${n instanceof Error?n.message:String(n)}`}}}});var Pb,Rb=g(()=>{"use strict";l();Pb={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var zn,$b=g(()=>{"use strict";l();Rb();$e();zn={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:Pb,execute:async r=>{let e=r.remote;try{let t=G(),o=e?["-a"]:[],n=await t.branch(o);return`Current Branch: ${n.current}
304
+ Summary: ${o.summary.changes} changes, ${o.summary.insertions} insertions, ${o.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will create a permanent commit in the repository history.",showArgs:["message"]}}});var Pb,Rb=g(()=>{"use strict";c();Pb={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 Kn,$b=g(()=>{"use strict";c();Rb();Ee();Kn={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:Pb,execute:async r=>{let e=r.path,t=r.sha,o=r.cloneDir;try{let n=z(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 Eb,Db=g(()=>{"use strict";c();Eb={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Jn,Ab=g(()=>{"use strict";c();Db();Ee();Jn={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:Eb,execute:async r=>{let e=r.remote;try{let t=z(),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 Eb,Db=g(()=>{"use strict";l();Eb={type:"object",properties:{name:{type:"string",description:"Name of the new branch."},checkout:{type:"boolean",description:"Whether to checkout the new branch after creating it.",default:!1},startPoint:{type:"string",description:"Optional start point (commit hash or branch name) for the new branch."}},required:["name"]}});var Hn,Ab=g(()=>{"use strict";l();Db();$e();Hn={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Eb,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 Mb,Nb=g(()=>{"use strict";l();Mb={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Kn,Ob=g(()=>{"use strict";l();Nb();$e();Kn={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Mb,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 Ib,jb=g(()=>{"use strict";l();Ib={type:"object",properties:{repo:{type:"string",description:'The repository to clone in "owner/repo" format (e.g., "microsoft/typescript").'},sha:{type:"string",description:"The commit SHA to checkout (always use SHAs, never branch names \u2014 handles force-pushes correctly)."},filter:{type:"string",description:'Git partial clone filter. "blob:none" (default) skips file blobs for a fast clone \u2014 blobs are fetched on demand when you read files or run git blame. Use "none" when you need immediate access to all file contents without extra fetches (e.g. heavy blame across many files).',default:"blob:none"},depth:{type:"number",description:"Commit history depth. Default 50 is enough for most PR reviews. Use 0 for full history when you need complete git log or blame across a long-lived file.",default:50},cloneRoot:{type:"string",description:"Override the local directory where clones are stored. Leave unset in almost all cases \u2014 the default is managed automatically."}},required:["repo","sha"]}});async function Lb(r){let e=0,t=await be.readdir(r,{withFileTypes:!0});for(let o of t){let n=ls.join(r,o.name);if(o.isDirectory())e+=await Lb(n);else if(o.isFile()){let s=await be.stat(n);e+=s.size}}return e}async function CC(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=ls.resolve(s,d),f=G(s),b=r.registry.get(e);if(b)try{if(await be.access(m),b.sha===t)return b.lastAccessedAt=Date.now(),m;await be.rm(m,{recursive:!0,force:!0}),r.totalBytes=Math.max(0,r.totalBytes-b.sizeBytes),r.registry.delete(e)}catch{r.totalBytes=Math.max(0,r.totalBytes-b.sizeBytes),r.registry.delete(e)}else try{await be.access(m),await be.rm(m,{recursive:!0,force:!0})}catch{}let h=["--no-checkout"];n>0&&h.push("--depth",n.toString()),o&&o!=="none"&&h.push("--filter",o);try{await f.clone(p,d,h);let T=G(m);try{let C=["origin",t];n>0&&C.push("--depth",n.toString()),await T.fetch(C)}catch{}await T.checkout(["--force",t]);let k=await Lb(m);return r.totalBytes+=k,r.registry.set(e,{cloneDir:m,repo:e,sha:t,sizeBytes:k,lastAccessedAt:Date.now()}),m}catch(T){try{await be.rm(m,{recursive:!0,force:!0})}catch{}throw T}}function kC(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}function Fa(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:Ib,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??xC,p=parseInt(process.env.TOOLPACK_GIT_CLONE_MAX_BYTES??"0",10)||vC,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 f=r.registry.get(o);if(f&&f.sha===n)return f.lastAccessedAt=Date.now(),JSON.stringify({cloneDir:f.cloneDir,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."});await r.evictIfNeeded(1e8,d);let b=await CC(r,o,n,s,i,c,t?.githubTokenStore,t?.config?.credentials);return JSON.stringify({cloneDir:b,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."})}catch(f){return`Error cloning repository: ${kC(f)}`}finally{m()}}}}var be,ls,xC,vC,Jn,Fb=g(()=>{"use strict";l();jb();$e();xe();ti();be=x(require("fs/promises"),1),ls=x(require("path"),1),xC=".toolpack/clones",vC=5e9;Jn=Fa(hc)});var qb={};ee(qb,{createGitCloneTool:()=>Fa,gitAddTool:()=>Un,gitBlameTool:()=>Bn,gitBranchCreateTool:()=>Hn,gitBranchListTool:()=>zn,gitCheckoutTool:()=>Kn,gitCloneTool:()=>Jn,gitCommitTool:()=>Gn,gitDiffTool:()=>qn,gitLogTool:()=>Wn,gitStatusTool:()=>Fn,gitToolsProject:()=>qa});var qa,Wa=g(()=>{"use strict";l();mb();fb();yb();wb();Cb();_b();$b();Ab();Ob();Fb();qa={manifest:{key:"git",name:"git-tools",displayName:"Git Version Control",version:"1.0.0",description:"Git operations for reading repository state, checking diffs, creating commits, and managing branches.",author:"Sajeer",tools:["git.status","git.diff","git.log","git.add","git.commit","git.blame","git.branch_list","git.branch_create","git.checkout","git.clone"],category:"version-control"},tools:[Fn,qn,Wn,Un,Gn,Bn,zn,Hn,Kn,Jn],dependencies:{"simple-git":"^3.27.0"}}});var Wb,Ub=g(()=>{"use strict";l();Wb={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});var Gb,Vn,Bb=g(()=>{"use strict";l();Ub();Gb=x(require("diff"),1);_();Vn={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:Wb,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 Gb.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var zb,Hb=g(()=>{"use strict";l();zb={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});var Kb,Ua,Qn,Jb=g(()=>{"use strict";l();Hb();Kb=x(require("diff"),1),Ua=require("fs");_();Qn={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:zb,execute:async r=>{let e=r.path,t=r.patch;y(`[diff.apply] execute path="${e}"`);try{let o=await Ua.promises.readFile(e,"utf8"),n=Kb.applyPatch(o,t);return n===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await Ua.promises.writeFile(e,n,"utf8"),`Successfully applied patch to ${e}`)}catch(o){return`Error applying patch: ${o instanceof Error?o.message:String(o)}`}},confirmation:{level:"high",reason:"This will apply a patch to files, which may corrupt them if the patch doesn't match.",showArgs:["path"]}}});var Vb,Qb=g(()=>{"use strict";l();Vb={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});var Xb,Yb,Xn,Zb=g(()=>{"use strict";l();Qb();Xb=x(require("diff"),1),Yb=require("fs"),Xn={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:Vb,execute:async r=>{let e=r.path,t=r.patch;try{let o=await Yb.promises.readFile(e,"utf8"),n=Xb.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 Mb,Nb=g(()=>{"use strict";c();Mb={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 Vn,Ob=g(()=>{"use strict";c();Nb();Ee();Vn={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Mb,execute:async r=>{let e=r.name,t=r.checkout,o=r.startPoint;try{let n=z();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 Ib,Lb=g(()=>{"use strict";c();Ib={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var Qn,jb=g(()=>{"use strict";c();Lb();Ee();Qn={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:Ib,execute:async r=>{let e=r.branch;try{return await z().checkout(e),`Successfully checked out: ${e}`}catch(t){return`Error checking out branch: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will switch branches, potentially losing uncommitted changes.",showArgs:["branch"]}}});var Fb,qb=g(()=>{"use strict";c();Fb={type:"object",properties:{repo:{type:"string",description:'The repository to clone in "owner/repo" format (e.g., "microsoft/typescript").'},sha:{type:"string",description:"The commit SHA to checkout (always use SHAs, never branch names \u2014 handles force-pushes correctly)."},filter:{type:"string",description:'Git partial clone filter. "blob:none" (default) skips file blobs for a fast clone \u2014 blobs are fetched on demand when you read files or run git blame. Use "none" when you need immediate access to all file contents without extra fetches (e.g. heavy blame across many files).',default:"blob:none"},depth:{type:"number",description:"Commit history depth. Default 50 is enough for most PR reviews. Use 0 for full history when you need complete git log or blame across a long-lived file.",default:50},cloneRoot:{type:"string",description:"Override the local directory where clones are stored. Leave unset in almost all cases \u2014 the default is managed automatically."}},required:["repo","sha"]}});async function Wb(r){let e=0,t=await Te.readdir(r,{withFileTypes:!0});for(let o of t){let n=ms.join(r,o.name);if(o.isDirectory())e+=await Wb(n);else if(o.isFile()){let s=await Te.stat(n);e+=s.size}}return e}async function PC(r,e,t,o,n,s,i,a){let p=`https://x-access-token:${await V(e,void 0,i,a)}@github.com/${e}.git`,d=e.replace("/","_"),m=ms.resolve(s,d),u=z(s),b=r.registry.get(e);if(b)try{if(await Te.access(m),b.sha===t)return b.lastAccessedAt=Date.now(),m;await Te.rm(m,{recursive:!0,force:!0}),r.totalBytes=Math.max(0,r.totalBytes-b.sizeBytes),r.registry.delete(e)}catch{r.totalBytes=Math.max(0,r.totalBytes-b.sizeBytes),r.registry.delete(e)}else try{await Te.access(m),await Te.rm(m,{recursive:!0,force:!0})}catch{}let h=["--no-checkout"];n>0&&h.push("--depth",n.toString()),o&&o!=="none"&&h.push("--filter",o);try{await u.clone(p,d,h);let T=z(m);try{let S=["origin",t];n>0&&S.push("--depth",n.toString()),await T.fetch(S)}catch{}await T.checkout(["--force",t]);let C=await Wb(m);return r.totalBytes+=C,r.registry.set(e,{cloneDir:m,repo:e,sha:t,sizeBytes:C,lastAccessedAt:Date.now()}),m}catch(T){try{await Te.rm(m,{recursive:!0,force:!0})}catch{}throw T}}function RC(r){return(r instanceof Error?r.message:String(r)).replace(/x-access-token:[^@]+@/g,"x-access-token:***@")}function Ua(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:Fb,execute:async(e,t)=>{let o=e.repo,n=e.sha,s=e.filter??"blob:none",i=e.depth??50,a=t?.config?.gitClone,l=e.cloneRoot??a?.cloneRoot??process.env.TOOLPACK_GIT_CLONE_ROOT??SC,p=parseInt(process.env.TOOLPACK_GIT_CLONE_MAX_BYTES??"0",10)||_C,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 Te.mkdir(l,{recursive:!0});let m=await r.acquireMutex(o);try{let u=r.registry.get(o);if(u&&u.sha===n)return u.lastAccessedAt=Date.now(),JSON.stringify({cloneDir:u.cloneDir,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."});await r.evictIfNeeded(1e8,d);let b=await PC(r,o,n,s,i,l,t?.githubTokenStore,t?.config?.credentials);return JSON.stringify({cloneDir:b,next:"Pass cloneDir to compatible git, filesystem, or coding tools to inspect this checkout."})}catch(u){return`Error cloning repository: ${RC(u)}`}finally{m()}}}}var Te,ms,SC,_C,Xn,Ub=g(()=>{"use strict";c();qb();Ee();ve();ri();Te=x(require("fs/promises"),1),ms=x(require("path"),1),SC=".toolpack/clones",_C=5e9;Xn=Ua(Tc)});var Gb={};te(Gb,{createGitCloneTool:()=>Ua,gitAddTool:()=>zn,gitBlameTool:()=>Kn,gitBranchCreateTool:()=>Vn,gitBranchListTool:()=>Jn,gitCheckoutTool:()=>Qn,gitCloneTool:()=>Xn,gitCommitTool:()=>Hn,gitDiffTool:()=>Gn,gitLogTool:()=>Bn,gitStatusTool:()=>Un,gitToolsProject:()=>Ga});var Ga,Ba=g(()=>{"use strict";c();fb();yb();wb();Cb();_b();$b();Ab();Ob();jb();Ub();Ga={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:[Un,Gn,Bn,zn,Hn,Kn,Jn,Vn,Qn,Xn],dependencies:{"simple-git":"^3.27.0"}}});var Bb,zb=g(()=>{"use strict";c();Bb={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});var Hb,Yn,Kb=g(()=>{"use strict";c();zb();Hb=x(require("diff"),1);P();Yn={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:Bb,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 Hb.createPatch(o,e,t,"","",{context:n})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var Jb,Vb=g(()=>{"use strict";c();Jb={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});var Qb,za,Zn,Xb=g(()=>{"use strict";c();Vb();Qb=x(require("diff"),1),za=require("fs");P();Zn={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:Jb,execute:async r=>{let e=r.path,t=r.patch;y(`[diff.apply] execute path="${e}"`);try{let o=await za.promises.readFile(e,"utf8"),n=Qb.applyPatch(o,t);return n===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await za.promises.writeFile(e,n,"utf8"),`Successfully applied patch to ${e}`)}catch(o){return`Error applying patch: ${o instanceof Error?o.message:String(o)}`}},confirmation:{level:"high",reason:"This will apply a patch to files, which may corrupt them if the patch doesn't match.",showArgs:["path"]}}});var Yb,Zb=g(()=>{"use strict";c();Yb={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});var eT,tT,er,oT=g(()=>{"use strict";c();Zb();eT=x(require("diff"),1),tT=require("fs"),er={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:Yb,execute:async r=>{let e=r.path,t=r.patch;try{let o=await tT.promises.readFile(e,"utf8"),n=eT.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 eT={};ee(eT,{diffApplyTool:()=>Qn,diffCreateTool:()=>Vn,diffPreviewTool:()=>Xn,diffToolsProject:()=>Ga});var Ga,Ba=g(()=>{"use strict";l();Bb();Jb();Zb();Ga={manifest:{key:"diff",name:"diff-tools",displayName:"Diff and Patch",version:"1.0.0",description:"Tools to create and apply unified diff changes to files safely.",author:"Sajeer",tools:["diff.create","diff.apply","diff.preview"],category:"diff"},tools:[Vn,Qn,Xn],dependencies:{diff:"^7.0.0"}}});var tT,oT=g(()=>{"use strict";l();tT={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 rt,cs=g(()=>{"use strict";l();rt=class{connectionString;constructor(e){this.connectionString=e}}});var za,Ha,Yn,nT=g(()=>{"use strict";l();za=x(require("better-sqlite3"),1),Ha=x(require("fs"),1);cs();Yn=class extends rt{getDb(){if(!Ha.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new za.default(this.connectionString,{readonly:!1})}async query(e,t=[]){let o=this.getDb();try{let n=o.prepare(e);return n.reader?n.all(t):(n.run(t),[])}finally{o.close()}}async execute(e,t=[]){let o=this.getDb();try{let s=o.prepare(e).run(t);return{changes:s.changes,lastInsertRowid:s.lastInsertRowid,raw:s}}finally{o.close()}}async getTables(){return(await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`PRAGMA table_info("${e}")`):await this.query("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")}static executeSession(e,t,o=[]){if(!Ha.existsSync(e))throw new Error(`Database file not found: ${e}`);let n=new za.default(e,{readonly:!1});try{let s=n.prepare(t);return s.reader?s.all(o):s.run(o)}finally{n.close()}}}});var rT,ps,sT=g(()=>{"use strict";l();rT=x(require("pg"),1);cs();ps=class extends rt{async getClient(){let e=new rT.default.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let o=await this.getClient();try{let n=this.convertSql(e);return(await o.query(n,t)).rows}finally{await o.end()}}async execute(e,t=[]){let o=await this.getClient();try{let n=this.convertSql(e),s=await o.query(n,t);return{changes:s.rowCount??0,raw:s}}finally{await o.end()}}async getTables(){return(await this.query("SELECT tablename as name FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`
310
+ ${n}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var nT={};te(nT,{diffApplyTool:()=>Zn,diffCreateTool:()=>Yn,diffPreviewTool:()=>er,diffToolsProject:()=>Ha});var Ha,Ka=g(()=>{"use strict";c();Kb();Xb();oT();Ha={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 rT,sT=g(()=>{"use strict";c();rT={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 it,ds=g(()=>{"use strict";c();it=class{connectionString;constructor(e){this.connectionString=e}}});var Ja,Va,tr,iT=g(()=>{"use strict";c();Ja=x(require("better-sqlite3"),1),Va=x(require("fs"),1);ds();tr=class extends it{getDb(){if(!Va.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Ja.default(this.connectionString,{readonly:!1})}async query(e,t=[]){let o=this.getDb();try{let n=o.prepare(e);return n.reader?n.all(t):(n.run(t),[])}finally{o.close()}}async execute(e,t=[]){let o=this.getDb();try{let s=o.prepare(e).run(t);return{changes:s.changes,lastInsertRowid:s.lastInsertRowid,raw:s}}finally{o.close()}}async getTables(){return(await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`PRAGMA table_info("${e}")`):await this.query("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")}static executeSession(e,t,o=[]){if(!Va.existsSync(e))throw new Error(`Database file not found: ${e}`);let n=new Ja.default(e,{readonly:!1});try{let s=n.prepare(t);return s.reader?s.all(o):s.run(o)}finally{n.close()}}}});var aT,us,lT=g(()=>{"use strict";c();aT=x(require("pg"),1);ds();us=class extends it{async getClient(){let e=new aT.default.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let o=await this.getClient();try{let n=this.convertSql(e);return(await o.query(n,t)).rows}finally{await o.end()}}async execute(e,t=[]){let o=await this.getClient();try{let n=this.convertSql(e),s=await o.query(n,t);return{changes:s.rowCount??0,raw:s}}finally{await o.end()}}async getTables(){return(await this.query("SELECT tablename as name FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`
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
- `)}}});var iT,ms,aT=g(()=>{"use strict";l();iT=x(require("mysql2/promise"),1);cs();ms=class extends rt{async getConnection(){return await iT.default.createConnection(this.connectionString)}async query(e,t=[]){let o=await this.getConnection();try{let[n]=await o.execute(e,t);return n}finally{await o.end()}}async execute(e,t=[]){let o=await this.getConnection();try{let[n]=await o.execute(e,t);return{changes:n.affectedRows,lastInsertRowid:n.insertId,raw:n}}finally{await o.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let o=Object.keys(t[0]);return t.map(n=>n[o[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[o]=await t.query("DESCRIBE ??",[e]);return o}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var ae,st=g(()=>{"use strict";l();nT();sT();aT();ae=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new ps(e):e.startsWith("mysql://")?new ms(e):e.startsWith("sqlite://")?new Yn(e.replace("sqlite://","")):new Yn(e)}}});var Zn,lT=g(()=>{"use strict";l();oT();st();_();Zn={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:tT,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 ae.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 cT,pT=g(()=>{"use strict";l();cT={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var er,mT=g(()=>{"use strict";l();pT();st();er={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:cT,execute:async r=>{let e=r.db,t=r.table;try{let n=await ae.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var dT,uT=g(()=>{"use strict";l();dT={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var tr,fT=g(()=>{"use strict";l();uT();st();tr={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:dT,execute:async r=>{let e=r.db;try{let o=await ae.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var gT,hT=g(()=>{"use strict";l();gT={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to insert into"},data:{type:"object",description:"Key-value pairs of column names and values to insert"}},required:["db","table","data"]}});var or,yT=g(()=>{"use strict";l();hT();st();or={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:gT,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 ae.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 bT,TT=g(()=>{"use strict";l();bT={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to update"},data:{type:"object",description:"Key-value pairs of column names and new values"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","data","where"]}});var nr,wT=g(()=>{"use strict";l();TT();st();nr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:bT,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 ae.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 xT,vT=g(()=>{"use strict";l();xT={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var rr,CT=g(()=>{"use strict";l();vT();st();rr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:xT,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await ae.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 kT,ST=g(()=>{"use strict";l();kT={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to count rows from"},where:{type:"string",description:"Optional WHERE clause condition"}},required:["db","table"]}});var sr,_T=g(()=>{"use strict";l();ST();st();sr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:kT,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 ae.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 PT={};ee(PT,{dbCountTool:()=>sr,dbDeleteTool:()=>rr,dbInsertTool:()=>or,dbQueryTool:()=>Zn,dbSchemaTool:()=>er,dbTablesTool:()=>tr,dbToolsProject:()=>Ka,dbUpdateTool:()=>nr});var Ka,Ja=g(()=>{"use strict";l();lT();mT();fT();yT();wT();CT();_T();Ka={manifest:{key:"db",name:"db-tools",displayName:"Database Tools",version:"1.0.0",description:"Stateless database operations enabling the AI to interact with local databases.",author:"Sajeer",tools:["db.query","db.schema","db.tables","db.insert","db.update","db.delete","db.count"],category:"database"},tools:[Zn,er,tr,or,nr,rr,sr],dependencies:{"better-sqlite3":"^11.3.0"}}});var RT,$T=g(()=>{"use strict";l();RT={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});var ET,it,ds=g(()=>{"use strict";l();ET=require("netlify"),it=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 ET.NetlifyAPI(t)}}});var ir,DT=g(()=>{"use strict";l();$T();ds();_();ir={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:RT,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 it.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 AT,MT=g(()=>{"use strict";l();AT={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},deployId:{type:"string",description:"The specific Deployment ID to check"}},required:["siteId","deployId"]}});var ar,NT=g(()=>{"use strict";l();MT();ds();ar={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:AT,execute:async(r,e)=>{let t=r.siteId,o=r.deployId;try{let s=await it.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 OT,IT=g(()=>{"use strict";l();OT={type:"object",properties:{siteId:{type:"string",description:"The Netlify Site ID"},limit:{type:"number",description:"Number of recent deployments to return. Defaults to 5.",default:5}},required:["siteId"]}});var lr,jT=g(()=>{"use strict";l();IT();ds();_();lr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:OT,execute:async(r,e)=>{let t=r.siteId,o=r.limit||5;y(`[cloud.list] execute siteId="${t}" limit=${o}`);try{let s=await it.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 LT={};ee(LT,{cloudDeployTool:()=>ir,cloudListTool:()=>lr,cloudStatusTool:()=>ar,cloudToolsProject:()=>Va});var Va,Qa=g(()=>{"use strict";l();DT();NT();jT();Va={manifest:{key:"cloud",name:"cloud-tools",displayName:"Cloud Deployment",version:"1.0.0",description:"Cloud deployment operations allowing the AI to publish directories directly to the internet.",author:"Sajeer",tools:["cloud.deploy","cloud.status","cloud.list"],category:"cloud"},tools:[ir,ar,lr],dependencies:{netlify:"^13.1.20"}}});var FT,qT,WT,UT,GT,BT=g(()=>{"use strict";l();FT="slack.chat.postMessage",qT="Post Slack Message",WT="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.",UT="slack",GT={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 Ct=g(()=>{"use strict";l()});function SC(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:SC(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 kt=g(()=>{"use strict";l()});async function _C(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 an,Xa=g(()=>{"use strict";l();BT();Ct();kt();an={name:FT,displayName:qT,description:WT,parameters:GT,category:UT,execute:_C}});var zT,HT,KT,JT,VT,QT=g(()=>{"use strict";l();zT="slack.chat.postEphemeral",HT="Post Ephemeral Slack Message",KT="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.",JT="slack",VT={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 PC(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 ln,Ya=g(()=>{"use strict";l();QT();Ct();kt();ln={name:zT,displayName:HT,description:KT,parameters:VT,category:JT,execute:PC}});var XT,YT,ZT,ew,tw,ow=g(()=>{"use strict";l();XT="slack.reactions.add",YT="Add Slack Reaction",ZT="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.",ew="slack",tw={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 RC(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 cn,Za=g(()=>{"use strict";l();ow();Ct();kt();cn={name:XT,displayName:YT,description:ZT,parameters:tw,category:ew,execute:RC}});var nw,rw,sw,iw,aw,lw=g(()=>{"use strict";l();nw="slack.conversations.history",rw="Get Slack Channel History",sw="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.",iw="slack",aw={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 $C(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]`:"",f=(p.text??"").replace(/\n/g," ").slice(0,200);return`[${p.ts}] ${d}${m}: ${f}`}).join(`
319
- `)}var pn,el=g(()=>{"use strict";l();lw();Ct();kt();pn={name:nw,displayName:rw,description:sw,parameters:aw,category:iw,execute:$C}});var cw,pw,mw,dw,uw,fw=g(()=>{"use strict";l();cw="slack.conversations.replies",pw="Get Slack Thread Replies",mw="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.",dw="slack",uw={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 EC(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 f=d.user?`user:${d.user}`:d.bot_id?`bot:${d.bot_id}`:"unknown",b=m===0?" [parent]":"",h=(d.text??"").replace(/\n/g," ").slice(0,200);return`[${d.ts}] ${f}${b}: ${h}`}).join(`
320
- `)}var mn,tl=g(()=>{"use strict";l();fw();Ct();kt();mn={name:cw,displayName:pw,description:mw,parameters:uw,category:dw,execute:EC}});var gw,hw,yw,bw,Tw,ww=g(()=>{"use strict";l();gw="slack.auth.test",hw="Slack Auth Test",yw="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.",bw="slack",Tw={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function DC(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 dn,ol=g(()=>{"use strict";l();ww();Ct();kt();dn={name:gw,displayName:hw,description:yw,parameters:Tw,category:bw,execute:DC}});var xw={};ee(xw,{slackAuthTestTool:()=>dn,slackChatPostEphemeralTool:()=>ln,slackChatPostMessageTool:()=>an,slackConversationsHistoryTool:()=>pn,slackConversationsRepliesTool:()=>mn,slackReactionsAddTool:()=>cn,slackToolsProject:()=>nl});var nl,rl=g(()=>{"use strict";l();Xa();Ya();Za();el();tl();ol();Xa();Ya();Za();el();tl();ol();nl={manifest:{key:"slack",name:"slack-tools",displayName:"Slack",version:"1.0.0",description:"Slack Web API tools \u2014 post messages, reply in threads, react to messages, read channel history, read thread replies, and verify bot identity.",author:"Toolpack",tools:["slack.chat.postMessage","slack.chat.postEphemeral","slack.reactions.add","slack.conversations.history","slack.conversations.replies","slack.auth.test"],category:"slack"},tools:[an,ln,cn,pn,mn,dn]}});function I(r,e){if(r.includes("\0")||r.includes(`
321
- `)||r.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return r}function AC(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
+ `)}}});var cT,fs,pT=g(()=>{"use strict";c();cT=x(require("mysql2/promise"),1);ds();fs=class extends it{async getConnection(){return await cT.default.createConnection(this.connectionString)}async query(e,t=[]){let o=await this.getConnection();try{let[n]=await o.execute(e,t);return n}finally{await o.end()}}async execute(e,t=[]){let o=await this.getConnection();try{let[n]=await o.execute(e,t);return{changes:n.affectedRows,lastInsertRowid:n.insertId,raw:n}}finally{await o.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let o=Object.keys(t[0]);return t.map(n=>n[o[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[o]=await t.query("DESCRIBE ??",[e]);return o}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var ce,at=g(()=>{"use strict";c();iT();lT();pT();ce=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new us(e):e.startsWith("mysql://")?new fs(e):e.startsWith("sqlite://")?new tr(e.replace("sqlite://","")):new tr(e)}}});var or,mT=g(()=>{"use strict";c();sT();at();P();or={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:rT,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 ce.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 dT,uT=g(()=>{"use strict";c();dT={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 nr,fT=g(()=>{"use strict";c();uT();at();nr={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:dT,execute:async r=>{let e=r.db,t=r.table;try{let n=await ce.getAdapter(e).getSchema(t);return JSON.stringify(n,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var gT,hT=g(()=>{"use strict";c();gT={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var rr,yT=g(()=>{"use strict";c();hT();at();rr={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:gT,execute:async r=>{let e=r.db;try{let o=await ce.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var bT,TT=g(()=>{"use strict";c();bT={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 sr,wT=g(()=>{"use strict";c();TT();at();sr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:bT,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 ce.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 xT,vT=g(()=>{"use strict";c();xT={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 ir,CT=g(()=>{"use strict";c();vT();at();ir={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:xT,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 ce.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 kT,ST=g(()=>{"use strict";c();kT={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 ar,_T=g(()=>{"use strict";c();ST();at();ar={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:kT,execute:async r=>{let e=r.db,t=r.table,o=r.where;try{let n=`DELETE FROM ${t} WHERE ${o}`,i=await ce.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 PT,RT=g(()=>{"use strict";c();PT={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 lr,$T=g(()=>{"use strict";c();RT();at();lr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:PT,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 ce.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 ET={};te(ET,{dbCountTool:()=>lr,dbDeleteTool:()=>ar,dbInsertTool:()=>sr,dbQueryTool:()=>or,dbSchemaTool:()=>nr,dbTablesTool:()=>rr,dbToolsProject:()=>Qa,dbUpdateTool:()=>ir});var Qa,Xa=g(()=>{"use strict";c();mT();fT();yT();wT();CT();_T();$T();Qa={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:[or,nr,rr,sr,ir,ar,lr],dependencies:{"better-sqlite3":"^11.3.0"}}});var DT,AT=g(()=>{"use strict";c();DT={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});var MT,lt,gs=g(()=>{"use strict";c();MT=require("netlify"),lt=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 MT.NetlifyAPI(t)}}});var cr,NT=g(()=>{"use strict";c();AT();gs();P();cr={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:DT,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 lt.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 OT,IT=g(()=>{"use strict";c();OT={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 pr,LT=g(()=>{"use strict";c();IT();gs();pr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:OT,execute:async(r,e)=>{let t=r.siteId,o=r.deployId;try{let s=await lt.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 jT,FT=g(()=>{"use strict";c();jT={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 mr,qT=g(()=>{"use strict";c();FT();gs();P();mr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:jT,execute:async(r,e)=>{let t=r.siteId,o=r.limit||5;y(`[cloud.list] execute siteId="${t}" limit=${o}`);try{let s=await lt.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 WT={};te(WT,{cloudDeployTool:()=>cr,cloudListTool:()=>mr,cloudStatusTool:()=>pr,cloudToolsProject:()=>Ya});var Ya,Za=g(()=>{"use strict";c();NT();LT();qT();Ya={manifest:{key:"cloud",name:"cloud-tools",displayName:"Cloud Deployment",version:"1.0.0",description:"Cloud deployment operations allowing the AI to publish directories directly to the internet.",author:"Sajeer",tools:["cloud.deploy","cloud.status","cloud.list"],category:"cloud"},tools:[cr,pr,mr],dependencies:{netlify:"^13.1.20"}}});var UT,GT,BT,zT,HT,KT=g(()=>{"use strict";c();UT="slack.chat.postMessage",GT="Post Slack Message",BT="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.",zT="slack",HT={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 ke(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 St=g(()=>{"use strict";c()});function $C(r){return{Authorization:`Bearer ${r}`,"Content-Type":"application/json; charset=utf-8"}}async function Se(r,e,t){let o=await fetch(`https://slack.com/api/${r}`,{method:"POST",headers:$C(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 _t=g(()=>{"use strict";c()});async function EC(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=ke(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 l=await Se("chat.postMessage",i,a),p=l.ts??"";return`Message posted. channel=${l.channel??t} ts=${p}`}var cn,el=g(()=>{"use strict";c();KT();St();_t();cn={name:UT,displayName:GT,description:BT,parameters:HT,category:zT,execute:EC}});var JT,VT,QT,XT,YT,ZT=g(()=>{"use strict";c();JT="slack.chat.postEphemeral",VT="Post Ephemeral Slack Message",QT="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.",XT="slack",YT={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 DC(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=ke(r.token,e?.config?.credentials),a={channel:t,user:o,text:n};return s&&(a.thread_ts=s),await Se("chat.postEphemeral",i,a),`Ephemeral message sent to user=${o} in channel=${t}.`}var pn,tl=g(()=>{"use strict";c();ZT();St();_t();pn={name:JT,displayName:VT,description:QT,parameters:YT,category:XT,execute:DC}});var ew,tw,ow,nw,rw,sw=g(()=>{"use strict";c();ew="slack.reactions.add",tw="Add Slack Reaction",ow="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.",nw="slack",rw={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 AC(r,e){let t=String(r.channel),o=String(r.timestamp),n=String(r.name),s=ke(r.token,e?.config?.credentials);try{await Se("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,ol=g(()=>{"use strict";c();sw();St();_t();mn={name:ew,displayName:tw,description:ow,parameters:rw,category:nw,execute:AC}});var iw,aw,lw,cw,pw,mw=g(()=>{"use strict";c();iw="slack.conversations.history",aw="Get Slack Channel History",lw="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.",cw="slack",pw={type:"object",properties:{channel:{type:"string",description:"Channel ID to fetch history from."},limit:{type:"integer",description:"Maximum number of messages to return. Defaults to 10, max 100."},oldest:{type:"string",description:"Only return messages after this Unix timestamp (inclusive)."},latest:{type:"string",description:"Only return messages before this Unix timestamp (exclusive)."},token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:["channel"]}});async function MC(r,e){let t=String(r.channel),o=typeof r.limit=="number"?Math.min(r.limit,100):10,n=ke(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 Se("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]`:"",u=(p.text??"").replace(/\n/g," ").slice(0,200);return`[${p.ts}] ${d}${m}: ${u}`}).join(`
319
+ `)}var dn,nl=g(()=>{"use strict";c();mw();St();_t();dn={name:iw,displayName:aw,description:lw,parameters:pw,category:cw,execute:MC}});var dw,uw,fw,gw,hw,yw=g(()=>{"use strict";c();dw="slack.conversations.replies",uw="Get Slack Thread Replies",fw="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.",gw="slack",hw={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 NC(r,e){let t=String(r.channel),o=String(r.ts),n=typeof r.limit=="number"?Math.min(r.limit,100):20,s=ke(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 l=(await Se("conversations.replies",s,i)).messages??[];return l.length===0?"No replies found.":l.map((d,m)=>{let u=d.user?`user:${d.user}`:d.bot_id?`bot:${d.bot_id}`:"unknown",b=m===0?" [parent]":"",h=(d.text??"").replace(/\n/g," ").slice(0,200);return`[${d.ts}] ${u}${b}: ${h}`}).join(`
320
+ `)}var un,rl=g(()=>{"use strict";c();yw();St();_t();un={name:dw,displayName:uw,description:fw,parameters:hw,category:gw,execute:NC}});var bw,Tw,ww,xw,vw,Cw=g(()=>{"use strict";c();bw="slack.auth.test",Tw="Slack Auth Test",ww="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.",xw="slack",vw={type:"object",properties:{token:{type:"string",description:"Slack bot token. Defaults to TOOLPACK_SLACK_BOT_TOKEN env var."}},required:[]}});async function OC(r,e){let t=ke(r.token,e?.config?.credentials),o=await Se("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,sl=g(()=>{"use strict";c();Cw();St();_t();fn={name:bw,displayName:Tw,description:ww,parameters:vw,category:xw,execute:OC}});var kw={};te(kw,{slackAuthTestTool:()=>fn,slackChatPostEphemeralTool:()=>pn,slackChatPostMessageTool:()=>cn,slackConversationsHistoryTool:()=>dn,slackConversationsRepliesTool:()=>un,slackReactionsAddTool:()=>mn,slackToolsProject:()=>il});var il,al=g(()=>{"use strict";c();el();tl();ol();nl();rl();sl();el();tl();ol();nl();rl();sl();il={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]}});function L(r,e){if(r.includes("\0")||r.includes(`
321
+ `)||r.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return r}function IC(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 Te(r,e,t=3e4){r.forEach((o,n)=>I(o,`kubectl argument #${n}`)),y(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return(0,vw.execFileSync)("kubectl",r,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return AC(o)}}function MC(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 Cw(r){if(!r)return;if(typeof r=="string")return r;let e=Object.entries(r).filter(([,t])=>t!==void 0&&t!=="");if(e.length)return e.map(([t,o])=>`${I(t,"label key")}=${I(o,"label value")}`).join(",")}var vw,Ee,cr,pr,mr,dr,ur,fr,gr,hr,yr,br,Tr,kw=g(()=>{"use strict";l();vw=require("child_process");_();Ee="kubernetes";cr={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:Ee,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter pods."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter pods.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the pod list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"If true, list pods across all namespaces.",default:!1}},required:[]},execute:async r=>{let e=["get","pods"],t=r.output;t?e.push("-o",t):e.push("-o","wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",I(r.namespace,"namespace"));let o=Cw(r.labelSelector)??r.labels;return o&&e.push("-l",I(o,"labels")),Te(e)}},pr={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:Ee,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to describe, such as pod, service, deployment."},name:{type:"string",description:"Resource name. Optional for cluster-wide descriptions."},namespace:{type:"string",description:"Namespace containing the resource."}},required:["resource"]},execute:async r=>{let t=["describe",I(r.resource,"resource")];return r.name&&t.push(I(r.name,"name")),r.namespace&&t.push("-n",I(r.namespace,"namespace")),Te(t)}},mr={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:Ee,parameters:{type:"object",properties:{podName:{type:"string",description:"The name of the pod to fetch logs from."},namespace:{type:"string",description:"Namespace of the pod."},container:{type:"string",description:"Container name inside the pod."},tailLines:{type:"number",description:"Number of log lines to show from the end.",default:100},since:{type:"string",description:"Return logs newer than a relative duration like 5m or 1h."}},required:["podName"]},execute:async r=>{let e=["logs",I(r.podName,"podName")];return r.container&&e.push("-c",I(r.container,"container")),r.namespace&&e.push("-n",I(r.namespace,"namespace")),typeof r.tailLines=="number"&&e.push("--tail",`${r.tailLines}`),r.since&&e.push("--since",I(r.since,"since")),Te(e)}},dr={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:Ee,parameters:{type:"object",properties:{path:{type:"string",description:"Path to the manifest file to apply."},manifest:{type:"string",description:"Inline YAML manifest to apply if no path is provided."},namespace:{type:"string",description:"Namespace to apply the manifest into, if supported by the manifest."},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without applying changes.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will change cluster state by applying a Kubernetes manifest.",showArgs:["path","namespace"]},execute:async r=>{let e=r.path,t=r.manifest,o=["apply"];if(r.dryRun&&o.push("--dry-run=client"),o.push("-f"),e)return o.push(I(e,"path")),r.namespace&&o.push("-n",I(r.namespace,"namespace")),Te(o);if(!t)throw new Error("Either path or manifest is required to apply a Kubernetes manifest.");return r.namespace&&o.push("-n",I(r.namespace,"namespace")),o.push("-"),Te(o,t)}},ur={name:"k8s.delete_resource",displayName:"Kubernetes Delete Resource",description:"Delete a Kubernetes resource by type and name, or delete resources from a manifest file.",category:Ee,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to delete, such as pod, service, deployment."},name:{type:"string",description:"Name of the resource to delete."},namespace:{type:"string",description:"Namespace containing the resource."},path:{type:"string",description:"Path to a manifest file that contains the resources to delete."},force:{type:"boolean",description:"Force deletion of the resource.",default:!1},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without deleting resources.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will delete resources from the Kubernetes cluster.",showArgs:["resource","name","path"]},execute:async r=>{let e=r.path,t=r.resource,o=r.name;if(e){let s=["delete"];return r.dryRun&&s.push("--dry-run=client"),s.push("-f",I(e,"path")),r.namespace&&s.push("-n",I(r.namespace,"namespace")),Te(s)}if(!t||!o)throw new Error("resource and name are required unless a manifest path is provided.");let n=["delete",I(t,"resource"),I(o,"name")];return r.namespace&&n.push("-n",I(r.namespace,"namespace")),r.force&&n.push("--force","--grace-period=0"),r.dryRun&&n.push("--dry-run=client"),Te(n)}},fr={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:Ee,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},output:{type:"string",description:"Output format for the service list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List services across all namespaces.",default:!1}},required:[]},execute:async r=>{let e=["get","services"],t=r.output;return e.push("-o",t||"wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",I(r.namespace,"namespace")),Te(e)}},gr={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:Ee,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter deployments."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter deployments.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the deployment list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List deployments across all namespaces.",default:!1}},required:[]},execute:async r=>{let e=["get","deployments"],t=r.output;e.push("-o",t||"wide"),r.allNamespaces&&e.push("--all-namespaces"),r.namespace&&!r.allNamespaces&&e.push("-n",I(r.namespace,"namespace"));let o=Cw(r.labelSelector)??r.labels;return o&&e.push("-l",I(o,"labels")),Te(e)}},hr={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:Ee,parameters:{type:"object",properties:{name:{type:"string",description:"ConfigMap name."},namespace:{type:"string",description:"Namespace containing the ConfigMap."},output:{type:"string",description:"Output format, such as yaml or json.",enum:["yaml","json"],default:"yaml"}},required:["name"]},execute:async r=>{let e=["get","configmap",I(r.name,"name"),"-o",r.output||"yaml"];return r.namespace&&e.push("-n",I(r.namespace,"namespace")),Te(e)}},yr={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:Ee,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>Te(["config","use-context",I(r.context,"context")])},br={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:Ee,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"])},Tr={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:Ee,parameters:{type:"object",properties:{name:{type:"string",description:"Deployment name to wait for."},namespace:{type:"string",description:"Namespace containing the deployment."},timeout:{type:"string",description:"Timeout duration, e.g. 300s or 5m.",default:"300s"}},required:["name"]},execute:async r=>{let e=r.timeout,t=["rollout","status",`deployment/${I(r.name,"name")}`,"--timeout",e||"300s"];return r.namespace&&t.push("-n",I(r.namespace,"namespace")),Te(t,void 0,MC(e))}}});var Sw={};ee(Sw,{k8sApplyManifestTool:()=>dr,k8sDeleteResourceTool:()=>ur,k8sDescribeTool:()=>pr,k8sGetConfigMapTool:()=>hr,k8sGetLogsTool:()=>mr,k8sGetNamespacesTool:()=>br,k8sListDeploymentsTool:()=>gr,k8sListPodsTool:()=>cr,k8sListServicesTool:()=>fr,k8sSwitchContextTool:()=>yr,k8sToolsProject:()=>sl,k8sWaitForDeploymentTool:()=>Tr});var sl,il=g(()=>{"use strict";l();kw();sl={manifest:{key:"k8s",name:"k8s-tools",displayName:"Kubernetes",version:"1.0.0",description:"Kubernetes command and cluster inspection tools for working with kubectl and manifests.",author:"toolpack-sdk",tools:["k8s.list_pods","k8s.describe","k8s.get_logs","k8s.apply_manifest","k8s.delete_resource","k8s.list_services","k8s.list_deployments","k8s.get_config_map","k8s.switch_context","k8s.get_namespaces","k8s.wait_for_deployment"],category:"kubernetes"},tools:[cr,pr,mr,dr,ur,fr,gr,hr,yr,br,Tr]}});function Lw(r){switch(r.mode){case"static":return new yl(r.tokens);case"jwt":return new bl(r);case"custom":return{verifyAccessToken:r.verifyAccessToken}}}async function Fw(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 bs,yl,bl,qw=g(()=>{"use strict";l();bs=require("jose");yl=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:[]}}},bl=class{JWKS;audience;issuer;constructor(e){this.JWKS=(0,bs.createRemoteJWKSet)(new URL(e.jwksUrl)),this.audience=e.audience,this.issuer=e.issuer}async verifyAccessToken(e){let{payload:t}=await(0,bs.jwtVerify)(e,this.JWKS,{audience:this.audience,issuer:this.issuer}),o=t.scope??t.scp,n=Array.isArray(o)?o.filter(i=>typeof i=="string"):typeof o=="string"?o.split(" ").filter(Boolean):[],s=typeof t.client_id=="string"?t.client_id:typeof t.sub=="string"?t.sub:"unknown";return{token:e,clientId:s,scopes:n,expiresAt:t.exp}}}});var Jw={};ee(Jw,{startMcpServer:()=>GC});async function GC(r,e,t){let o=new zw.Server({name:e.serverName??"Toolpack SDK",version:e.serverVersion??"2.0.0"},{capabilities:{tools:{}}});if(o.setRequestHandler(Ts.ListToolsRequestSchema,async()=>{if(e.searchMode){let i=HC(r,e),a=Je(),c=i.map(p=>{let d=Uw(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,...Ww(e)]}}return{tools:[...Tl(r,e.expose).map(i=>{let a=Uw(i);return{name:i.name,description:i.description??"",inputSchema:i.parameters??{type:"object",properties:{}},...a!==void 0&&{annotations:a}}}),...Ww(e)]}}),o.setRequestHandler(Ts.CallToolRequestSchema,async n=>{let{name:s,arguments:i}=n.params;if(e.searchMode&&pt(s)){if(!t)return Ue("tool.search is not available: searchFn was not provided to startMcpServer.",!0);try{let c=t(i??{});return Ue(c)}catch(c){let p=c instanceof Error?c.message:String(c);return Ue(`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 Ue(`Agent not found: ${c}`,!0);try{let d=await p.invoke(i??{});return Ue(d)}catch(d){let m=d instanceof Error?d.message:String(d);return Ue(`Agent error (${c}): ${m}`,!0)}}let a=BC(r,s,e.expose);if(!a)return Ue(`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 Ue(p)}catch(c){let p=c instanceof Error?c.message:String(c);return Ue(`Error executing ${s}: ${p}`,!0)}}),e.transport==="stdio"){let n=new Hw.StdioServerTransport;return await o.connect(n),{get toolCount(){return Tl(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 Kw.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,Bw.randomUUID)()}),i=e.auth?Lw(e.auth):null,a=(0,Gw.createServer)(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 Fw(p,d,e.auth,i).catch(f=>(S(`[MCP Server] Auth error: ${f instanceof Error?f.message:String(f)}`),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=f=>{d(f.code==="EADDRINUSE"?new Error(`MCP HTTP server failed to start: port ${n} is already in use.`):f)};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 Tl(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 Tl(r,e){return e?e.categories?.length?r.getByCategories(e.categories):e.tools?.length?r.getByNames(e.tools):r.getEnabled():r.getEnabled()}function BC(r,e,t){let o=r.get(e);if(o)return t?.categories?.length?new Set(t.categories).has(o.category)?o:void 0:t?.tools?.length?t.tools.includes(e)?o:void 0:zC(r,o,e)?o:void 0}function zC(r,e,t){let{enabledTools:o,enabledToolCategories:n}=r.getConfig();return o.length===0&&n.length===0?!0:o.includes(t)||n.includes(e.category)}function Ww(r){return(r.agents??[]).map(e=>({name:`agent.${e.name}`,description:e.description,inputSchema:e.inputSchema??{type:"object",properties:{}}}))}function HC(r,e){let t=r.getConfig().toolSearch;if(!t)return[];let o=r.getByNames(t.alwaysLoadedTools),n=r.getByCategories(t.alwaysLoadedCategories),s=new Set([Ke]),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 Uw(r){if(r.annotations)return r.annotations;if(r.confirmation)return{destructiveHint:!0}}function Ue(r,e=!1){return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r,null,2)}],isError:e}}var Gw,Bw,zw,Hw,Kw,Ts,Vw=g(()=>{"use strict";l();Gw=require("http"),Bw=require("crypto"),zw=require("@modelcontextprotocol/sdk/server/index.js"),Hw=require("@modelcontextprotocol/sdk/server/stdio.js"),Kw=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Ts=require("@modelcontextprotocol/sdk/types.js");_();qw();vn()});var ZC={};ee(ZC,{AGENT_MODE:()=>fl,AGENT_PLANNING_PROMPT:()=>hs,AGENT_WORKFLOW:()=>ml,AIClient:()=>kn,AnthropicAdapter:()=>Sn,AnthropicVertexAdapter:()=>_n,AuthenticationError:()=>ue,BM25Engine:()=>ks,BM25SearchEngine:()=>Et,BUILT_IN_MODES:()=>vr,CHAT_MODE:()=>gl,CHAT_WORKFLOW:()=>ul,CODING_MODE:()=>hl,CODING_PLANNING_PROMPT:()=>Ow,CODING_WORKFLOW:()=>dl,CONFIG_DIR_NAME:()=>Cl,CONFIG_FILE_NAME:()=>kl,ConnectionError:()=>He,ContextWindowConfigError:()=>Ps,ContextWindowExceededError:()=>Rr,ContextWindowStateManager:()=>Ar,ConversationNotFoundError:()=>Rs,DEFAULT_MODE_NAME:()=>_t,DEFAULT_TOOLS_CONFIG:()=>te,DEFAULT_TOOL_SEARCH_CONFIG:()=>Wl,DEFAULT_WORKFLOW:()=>WC,DEFAULT_WORKFLOW_CONFIG:()=>ys,FILE_LIMITS:()=>cx,GeminiAdapter:()=>Rn,InMemoryConversationStore:()=>xs,InsufficientContextError:()=>$r,InvalidRequestError:()=>M,McpClient:()=>fn,McpConnectionError:()=>Ie,McpTimeoutError:()=>wr,McpToolManager:()=>xr,ModeRegistry:()=>gn,OllamaAdapter:()=>et,OllamaProvider:()=>Nt,OpenAIAdapter:()=>ht,OpenRouterAdapter:()=>Dn,PageError:()=>Ss,Planner:()=>hn,ProviderAdapter:()=>Q,ProviderError:()=>L,RateLimitError:()=>ie,RuleLoader:()=>ft,SDKError:()=>O,SQLiteConversationStore:()=>vs,SummarizationError:()=>Er,TOOLPACK_DIR_NAME:()=>vl,TOOL_SEARCH_NAME:()=>Ke,TimeoutError:()=>_s,ToolDiscoveryCache:()=>ct,ToolRegistry:()=>un,ToolRouter:()=>Dt,Toolpack:()=>xl,VertexAIAdapter:()=>Pn,WorkflowExecutor:()=>Cr,addBypassRule:()=>cc,buildSummarizedHistory:()=>kx,cloudDeployTool:()=>ir,cloudListTool:()=>lr,cloudStatusTool:()=>ar,cloudToolsProject:()=>Va,codingExtractFunctionTool:()=>rn,codingFindReferencesTool:()=>Qo,codingFindSymbolTool:()=>Ko,codingGetCallHierarchyTool:()=>sn,codingGetDiagnosticsTool:()=>on,codingGetExportsTool:()=>nn,codingGetImportsTool:()=>Vo,codingGetOutlineTool:()=>tn,codingGetSymbolsTool:()=>Jo,codingGoToDefinitionTool:()=>Xo,codingMultiFileEditTool:()=>Yo,codingRefactorRenameTool:()=>en,codingToolsProject:()=>ja,countTokens:()=>Es,createContextWindowStateManager:()=>Ls,createMcpToolProject:()=>fs,createMode:()=>Iw,createSkillTools:()=>Nw,createSummarizationReport:()=>Sx,createSummarySystemMessage:()=>Dr,createToolProject:()=>Ew,dbCountTool:()=>sr,dbDeleteTool:()=>rr,dbInsertTool:()=>or,dbQueryTool:()=>Zn,dbSchemaTool:()=>er,dbTablesTool:()=>tr,dbToolsProject:()=>Ka,dbUpdateTool:()=>nr,diffApplyTool:()=>Qn,diffCreateTool:()=>Vn,diffPreviewTool:()=>Xn,diffToolsProject:()=>Ga,disconnectMcpToolProject:()=>gs,ensureGlobalConfigDir:()=>Pl,ensureLocalConfigDir:()=>JC,estimateSummaryTokens:()=>Il,estimateTokenCount:()=>Le,execKillTool:()=>uo,execListProcessesTool:()=>fo,execReadOutputTool:()=>po,execRunBackgroundTool:()=>lo,execRunBlockingTool:()=>co,execRunShellTool:()=>ao,execRunTool:()=>io,execTailOutputTool:()=>mo,execToolsProject:()=>Ai,extractConversationKeypoints:()=>Cx,fetchUrlAsBase64:()=>Hs,fsAppendFileTool:()=>qt,fsBatchReadTool:()=>ro,fsBatchWriteTool:()=>so,fsCopyTool:()=>Vt,fsCreateDirTool:()=>Kt,fsDeleteDirTool:()=>no,fsDeleteFileTool:()=>Ut,fsExistsTool:()=>Gt,fsGlobTool:()=>oo,fsListDirTool:()=>zt,fsMoveTool:()=>Jt,fsReadFileRangeTool:()=>Xt,fsReadFileTool:()=>It,fsReplaceInFileTool:()=>Zt,fsSearchTool:()=>Yt,fsStatTool:()=>Bt,fsToolsProject:()=>vi,fsTreeTool:()=>to,fsWriteFileTool:()=>Lt,generateSummarizationPrompt:()=>Ol,generateToolCategoriesPrompt:()=>Mr,getContextWindowPercentage:()=>Tx,getDefaultSlmModel:()=>mc,getGlobalConfigDir:()=>Sl,getGlobalConfigPath:()=>Sr,getGlobalToolpackDir:()=>Zw,getLocalConfigDir:()=>_l,getLocalConfigPath:()=>_r,getLocalToolpackDir:()=>ex,getMessageStats:()=>vx,getMimeType:()=>Us,getOllamaBaseUrl:()=>En,getOllamaProviderEntries:()=>lc,getRegisteredSlmModels:()=>uc,getRuntimeConfigStatus:()=>QC,getSafeOutputReserve:()=>Ds,getToolSearchSchema:()=>Je,getToolpackConfig:()=>Lr,getUserHomeDir:()=>Yw,gitAddTool:()=>Un,gitBlameTool:()=>Bn,gitBranchCreateTool:()=>Hn,gitBranchListTool:()=>zn,gitCheckoutTool:()=>Kn,gitCloneTool:()=>Jn,gitCommitTool:()=>Gn,gitDiffTool:()=>qn,gitLogTool:()=>Wn,gitStatusTool:()=>Fn,gitToolsProject:()=>qa,githubContentsGetTextTool:()=>Po,githubGraphqlExecuteTool:()=>_o,githubIssuesCommentsCreateTool:()=>No,githubPrDiffGetTool:()=>Do,githubPrFilesListTool:()=>Ao,githubPrReviewCommentsReplyTool:()=>Eo,githubPrReviewThreadsListTool:()=>Ro,githubPrReviewThreadsResolveTool:()=>$o,githubPrReviewsSubmitTool:()=>Mo,githubToolsProject:()=>sa,groupMessagesByRole:()=>xx,handleContextWindowError:()=>mx,httpDeleteTool:()=>Co,httpDownloadTool:()=>So,httpGetTool:()=>wo,httpPostTool:()=>xo,httpPutTool:()=>vo,httpToolsProject:()=>Ji,initializeGlobalConfigIfFirstRun:()=>XC,isContextWindowError:()=>px,isDataUri:()=>Gs,isRegisteredSlm:()=>dc,isToolSearchTool:()=>pt,k8sApplyManifestTool:()=>dr,k8sDeleteResourceTool:()=>ur,k8sDescribeTool:()=>pr,k8sGetConfigMapTool:()=>hr,k8sGetLogsTool:()=>mr,k8sGetNamespacesTool:()=>br,k8sListDeploymentsTool:()=>gr,k8sListPodsTool:()=>cr,k8sListServicesTool:()=>fr,k8sSwitchContextTool:()=>yr,k8sToolsProject:()=>sl,k8sWaitForDeploymentTool:()=>Tr,loadFullConfig:()=>al,loadRuntimeConfig:()=>VC,loadToolsConfig:()=>Pw,mergeSummarizationResults:()=>_x,normalizeImagePart:()=>Zl,ollamaRequest:()=>Pe,ollamaStream:()=>Fr,parseDataUri:()=>Bs,parseFileEnvelope:()=>Ye,parseSkillFile:()=>tx,parseSummarizationResponse:()=>js,prepareSummarizationRequest:()=>Is,pruneMessages:()=>Ms,readFileAsBase64:()=>zs,reloadToolpackConfig:()=>ac,removeBypassRule:()=>pc,saveToolsConfig:()=>Rw,slackAuthTestTool:()=>dn,slackChatPostEphemeralTool:()=>ln,slackChatPostMessageTool:()=>an,slackConversationsHistoryTool:()=>pn,slackConversationsRepliesTool:()=>mn,slackReactionsAddTool:()=>cn,slackToolsProject:()=>nl,systemCwdTool:()=>bo,systemDiskUsageTool:()=>To,systemEnvTool:()=>ho,systemInfoTool:()=>go,systemSetEnvTool:()=>yo,systemToolsProject:()=>Wi,toDataUri:()=>Yl,toolSearchDefinition:()=>Fe,truncateMessage:()=>wx,validateSummarizationResult:()=>Os,webExtractLinksTool:()=>Lo,webFeedTool:()=>Uo,webFetchTool:()=>Oo,webMapTool:()=>Fo,webMetadataTool:()=>qo,webScrapeTool:()=>jo,webScreenshotTool:()=>Go,webSearchTool:()=>Io,webSitemapTool:()=>Wo,webToolsProject:()=>ba,wouldExceedContextWindow:()=>bx});module.exports=lx(ZC);l();l();var cx={image:{maxBytes:10485760},document:{maxBytes:10485760,maxPages:20}};pe();l();var Vl=require("events");pe();l();pe();async function Ml(r,e={}){let{maxRetries:t=3,backoffMs:o=[1e4,3e4,6e4],isRetryable:n=i=>i instanceof ie,onRetry:s}=e;for(let i=0;i<=t;i++)try{return await r()}catch(a){if(n(a)&&i<t){let c=a?.retryAfter!=null?a.retryAfter*1e3:o[i]??o[o.length-1]??6e4;s?.(i+1,c,a),await new Promise(p=>setTimeout(p,c));continue}throw a}throw new ie("Rate limit retries exhausted")}l();pe();var wn=class extends O{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 we(r,e,t=3e4){r.forEach((o,n)=>L(o,`kubectl argument #${n}`)),y(`[k8s-tools] execute: kubectl ${r.join(" ")}`);try{return(0,Sw.execFileSync)("kubectl",r,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return IC(o)}}function LC(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 _w(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])=>`${L(t,"label key")}=${L(o,"label value")}`).join(",")}var Sw,De,dr,ur,fr,gr,hr,yr,br,Tr,wr,xr,vr,Pw=g(()=>{"use strict";c();Sw=require("child_process");P();De="kubernetes";dr={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:De,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",L(r.namespace,"namespace"));let o=_w(r.labelSelector)??r.labels;return o&&e.push("-l",L(o,"labels")),we(e)}},ur={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:De,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",L(r.resource,"resource")];return r.name&&t.push(L(r.name,"name")),r.namespace&&t.push("-n",L(r.namespace,"namespace")),we(t)}},fr={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:De,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",L(r.podName,"podName")];return r.container&&e.push("-c",L(r.container,"container")),r.namespace&&e.push("-n",L(r.namespace,"namespace")),typeof r.tailLines=="number"&&e.push("--tail",`${r.tailLines}`),r.since&&e.push("--since",L(r.since,"since")),we(e)}},gr={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:De,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(L(e,"path")),r.namespace&&o.push("-n",L(r.namespace,"namespace")),we(o);if(!t)throw new Error("Either path or manifest is required to apply a Kubernetes manifest.");return r.namespace&&o.push("-n",L(r.namespace,"namespace")),o.push("-"),we(o,t)}},hr={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:De,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",L(e,"path")),r.namespace&&s.push("-n",L(r.namespace,"namespace")),we(s)}if(!t||!o)throw new Error("resource and name are required unless a manifest path is provided.");let n=["delete",L(t,"resource"),L(o,"name")];return r.namespace&&n.push("-n",L(r.namespace,"namespace")),r.force&&n.push("--force","--grace-period=0"),r.dryRun&&n.push("--dry-run=client"),we(n)}},yr={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:De,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",L(r.namespace,"namespace")),we(e)}},br={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:De,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",L(r.namespace,"namespace"));let o=_w(r.labelSelector)??r.labels;return o&&e.push("-l",L(o,"labels")),we(e)}},Tr={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:De,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",L(r.name,"name"),"-o",r.output||"yaml"];return r.namespace&&e.push("-n",L(r.namespace,"namespace")),we(e)}},wr={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:De,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async r=>we(["config","use-context",L(r.context,"context")])},xr={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:De,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=>we(["get","namespaces","-o",r.output||"wide"])},vr={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:De,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/${L(r.name,"name")}`,"--timeout",e||"300s"];return r.namespace&&t.push("-n",L(r.namespace,"namespace")),we(t,void 0,LC(e))}}});var Rw={};te(Rw,{k8sApplyManifestTool:()=>gr,k8sDeleteResourceTool:()=>hr,k8sDescribeTool:()=>ur,k8sGetConfigMapTool:()=>Tr,k8sGetLogsTool:()=>fr,k8sGetNamespacesTool:()=>xr,k8sListDeploymentsTool:()=>br,k8sListPodsTool:()=>dr,k8sListServicesTool:()=>yr,k8sSwitchContextTool:()=>wr,k8sToolsProject:()=>ll,k8sWaitForDeploymentTool:()=>vr});var ll,cl=g(()=>{"use strict";c();Pw();ll={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:[dr,ur,fr,gr,hr,yr,br,Tr,wr,xr,vr]}});function Ww(r){switch(r.mode){case"static":return new wl(r.tokens);case"jwt":return new xl(r);case"custom":return{verifyAccessToken:r.verifyAccessToken}}}async function Uw(r,e,t,o){let n=r.headers.authorization,s=typeof n=="string"&&n.startsWith("Bearer ")?n.slice(7):null;if(!s)return e.writeHead(401,{"WWW-Authenticate":"Bearer"}).end(),!1;let i;try{i=await o.verifyAccessToken(s)}catch{return e.writeHead(401,{"WWW-Authenticate":"Bearer"}).end(),!1}let a="requiredScopes"in t?t.requiredScopes:void 0;if(a?.length){let l=new Set(i.scopes),p=a.filter(d=>!l.has(d));if(p.length>0)return e.writeHead(403).end(`Missing required scopes: ${p.join(", ")}`),!1}return r.auth=i,!0}var xs,wl,xl,Gw=g(()=>{"use strict";c();xs=require("jose");wl=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:[]}}},xl=class{JWKS;audience;issuer;constructor(e){this.JWKS=(0,xs.createRemoteJWKSet)(new URL(e.jwksUrl)),this.audience=e.audience,this.issuer=e.issuer}async verifyAccessToken(e){let{payload:t}=await(0,xs.jwtVerify)(e,this.JWKS,{audience:this.audience,issuer:this.issuer}),o=t.scope??t.scp,n=Array.isArray(o)?o.filter(i=>typeof i=="string"):typeof o=="string"?o.split(" ").filter(Boolean):[],s=typeof t.client_id=="string"?t.client_id:typeof t.sub=="string"?t.sub:"unknown";return{token:e,clientId:s,scopes:n,expiresAt:t.exp}}}});var Xw={};te(Xw,{startMcpServer:()=>KC});async function KC(r,e,t){let o=new Jw.Server({name:e.serverName??"Toolpack SDK",version:e.serverVersion??"2.0.0"},{capabilities:{tools:{}}});if(o.setRequestHandler(vs.ListToolsRequestSchema,async()=>{if(e.searchMode){let i=QC(r,e),a=Qe(),l=i.map(p=>{let d=zw(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}},...l,...Bw(e)]}}return{tools:[...vl(r,e.expose).map(i=>{let a=zw(i);return{name:i.name,description:i.description??"",inputSchema:i.parameters??{type:"object",properties:{}},...a!==void 0&&{annotations:a}}}),...Bw(e)]}}),o.setRequestHandler(vs.CallToolRequestSchema,async n=>{let{name:s,arguments:i}=n.params;if(e.searchMode&&dt(s)){if(!t)return Be("tool.search is not available: searchFn was not provided to startMcpServer.",!0);try{let l=t(i??{});return Be(l)}catch(l){let p=l instanceof Error?l.message:String(l);return Be(`tool.search error: ${p}`,!0)}}if(s.startsWith("agent.")){let l=s.slice(6),p=(e.agents??[]).find(d=>d.name===l);if(!p)return Be(`Agent not found: ${l}`,!0);try{let d=await p.invoke(i??{});return Be(d)}catch(d){let m=d instanceof Error?d.message:String(d);return Be(`Agent error (${l}): ${m}`,!0)}}let a=JC(r,s,e.expose);if(!a)return Be(`Tool not found: ${s}`,!0);try{let l={workspaceRoot:process.cwd(),config:r.getConfig().additionalConfigurations??{},log:d=>k(`[MCP Tool] ${d}`),processRegistry:r.runtimeContext?.processRegistry,githubTokenStore:r.runtimeContext?.githubTokenStore},p=await a.execute(i??{},l);return Be(p)}catch(l){let p=l instanceof Error?l.message:String(l);return Be(`Error executing ${s}: ${p}`,!0)}}),e.transport==="stdio"){let n=new Vw.StdioServerTransport;return await o.connect(n),{get toolCount(){return vl(r,e.expose).length},port:0,stop:async()=>{await o.close()}}}if(e.transport==="http"){let n=e.port??3e3;e.auth||k("[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 Qw.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,Kw.randomUUID)()}),i=e.auth?Ww(e.auth):null,a=(0,Hw.createServer)(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 Uw(p,d,e.auth,i).catch(u=>(k(`[MCP Server] Auth error: ${u instanceof Error?u.message:String(u)}`),d.headersSent||d.writeHead(500).end("Internal Server Error"),!1))||s.handleRequest(p,d).catch(m=>{k(`[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=u=>{d(u.code==="EADDRINUSE"?new Error(`MCP HTTP server failed to start: port ${n} is already in use.`):u)};a.once("error",m),a.listen(n,()=>{a.off("error",m),p()})})}catch(p){throw await o.close().catch(()=>{}),p}let l=a.address().port;return{get toolCount(){return vl(r,e.expose).length},port:l,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 vl(r,e){return e?e.categories?.length?r.getByCategories(e.categories):e.tools?.length?r.getByNames(e.tools):r.getEnabled():r.getEnabled()}function JC(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:VC(r,o,e)?o:void 0}function VC(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 Bw(r){return(r.agents??[]).map(e=>({name:`agent.${e.name}`,description:e.description,inputSchema:e.inputSchema??{type:"object",properties:{}}}))}function QC(r,e){let t=r.getConfig().toolSearch;if(!t)return[];let o=r.getByNames(t.alwaysLoadedTools),n=r.getByCategories(t.alwaysLoadedCategories),s=new Set([Ve]),i=[...o,...n].filter(a=>s.has(a.name)?!1:(s.add(a.name),!0));if(e.expose?.categories?.length){let a=new Set(e.expose.categories);return i.filter(l=>a.has(l.category))}if(e.expose?.tools?.length){let a=new Set(e.expose.tools);return i.filter(l=>a.has(l.name))}return i}function zw(r){if(r.annotations)return r.annotations;if(r.confirmation)return{destructiveHint:!0}}function Be(r,e=!1){return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r,null,2)}],isError:e}}var Hw,Kw,Jw,Vw,Qw,vs,Yw=g(()=>{"use strict";c();Hw=require("http"),Kw=require("crypto"),Jw=require("@modelcontextprotocol/sdk/server/index.js"),Vw=require("@modelcontextprotocol/sdk/server/stdio.js"),Qw=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),vs=require("@modelcontextprotocol/sdk/types.js");P();Gw();Sn()});var nk={};te(nk,{AGENT_MODE:()=>yl,AGENT_PLANNING_PROMPT:()=>Ts,AGENT_WORKFLOW:()=>fl,AIClient:()=>Pn,AbortedError:()=>A,AnthropicAdapter:()=>Rn,AnthropicVertexAdapter:()=>$n,AuthenticationError:()=>fe,BM25Engine:()=>Ps,BM25SearchEngine:()=>At,BUILT_IN_MODES:()=>Sr,CHAT_MODE:()=>bl,CHAT_WORKFLOW:()=>hl,CODING_MODE:()=>Tl,CODING_PLANNING_PROMPT:()=>jw,CODING_WORKFLOW:()=>gl,CONFIG_DIR_NAME:()=>_l,CONFIG_FILE_NAME:()=>Pl,ConnectionError:()=>Je,ContextWindowConfigError:()=>Es,ContextWindowExceededError:()=>Dr,ContextWindowStateManager:()=>Or,ConversationNotFoundError:()=>Ds,DEFAULT_MODE_NAME:()=>Rt,DEFAULT_TOOLS_CONFIG:()=>oe,DEFAULT_TOOL_SEARCH_CONFIG:()=>Bl,DEFAULT_WORKFLOW:()=>zC,DEFAULT_WORKFLOW_CONFIG:()=>ws,FILE_LIMITS:()=>dx,GeminiAdapter:()=>Dn,InMemoryConversationStore:()=>ks,InsufficientContextError:()=>Ar,InvalidRequestError:()=>O,McpClient:()=>hn,McpConnectionError:()=>Le,McpTimeoutError:()=>Cr,McpToolManager:()=>kr,ModeRegistry:()=>yn,OllamaAdapter:()=>ot,OllamaProvider:()=>It,OpenAIAdapter:()=>bt,OpenRouterAdapter:()=>Nn,PageError:()=>Rs,Planner:()=>bn,ProviderAdapter:()=>X,ProviderError:()=>F,RateLimitError:()=>ae,RuleLoader:()=>ht,SDKError:()=>M,SQLiteConversationStore:()=>Ss,SummarizationError:()=>Mr,TOOLPACK_DIR_NAME:()=>Sl,TOOL_SEARCH_NAME:()=>Ve,TimeoutError:()=>$s,ToolDiscoveryCache:()=>mt,ToolRegistry:()=>gn,ToolRouter:()=>Mt,Toolpack:()=>kl,VertexAIAdapter:()=>En,WorkflowExecutor:()=>_r,addBypassRule:()=>dc,buildSummarizedHistory:()=>Rx,cloudDeployTool:()=>cr,cloudListTool:()=>mr,cloudStatusTool:()=>pr,cloudToolsProject:()=>Ya,codingExtractFunctionTool:()=>an,codingFindReferencesTool:()=>Yo,codingFindSymbolTool:()=>Vo,codingGetCallHierarchyTool:()=>ln,codingGetDiagnosticsTool:()=>rn,codingGetExportsTool:()=>sn,codingGetImportsTool:()=>Xo,codingGetOutlineTool:()=>nn,codingGetSymbolsTool:()=>Qo,codingGoToDefinitionTool:()=>Zo,codingMultiFileEditTool:()=>en,codingRefactorRenameTool:()=>on,codingToolsProject:()=>qa,countTokens:()=>Ms,createContextWindowStateManager:()=>Ws,createMcpToolProject:()=>ys,createMode:()=>Fw,createSkillTools:()=>Lw,createSummarizationReport:()=>$x,createSummarySystemMessage:()=>Nr,createToolProject:()=>Mw,dbCountTool:()=>lr,dbDeleteTool:()=>ar,dbInsertTool:()=>sr,dbQueryTool:()=>or,dbSchemaTool:()=>nr,dbTablesTool:()=>rr,dbToolsProject:()=>Qa,dbUpdateTool:()=>ir,diffApplyTool:()=>Zn,diffCreateTool:()=>Yn,diffPreviewTool:()=>er,diffToolsProject:()=>Ha,disconnectMcpToolProject:()=>bs,ensureGlobalConfigDir:()=>El,ensureLocalConfigDir:()=>YC,estimateSummaryTokens:()=>Fl,estimateTokenCount:()=>qe,execKillTool:()=>go,execListProcessesTool:()=>ho,execReadOutputTool:()=>uo,execRunBackgroundTool:()=>po,execRunBlockingTool:()=>mo,execRunShellTool:()=>co,execRunTool:()=>lo,execTailOutputTool:()=>fo,execToolsProject:()=>Oi,extractConversationKeypoints:()=>Px,fetchUrlAsBase64:()=>Vs,fsAppendFileTool:()=>Ut,fsBatchReadTool:()=>io,fsBatchWriteTool:()=>ao,fsCopyTool:()=>Xt,fsCreateDirTool:()=>Vt,fsDeleteDirTool:()=>so,fsDeleteFileTool:()=>Bt,fsExistsTool:()=>zt,fsGlobTool:()=>ro,fsListDirTool:()=>Kt,fsMoveTool:()=>Qt,fsReadFileRangeTool:()=>Zt,fsReadFileTool:()=>jt,fsReplaceInFileTool:()=>to,fsSearchTool:()=>eo,fsStatTool:()=>Ht,fsToolsProject:()=>Si,fsTreeTool:()=>no,fsWriteFileTool:()=>qt,generateSummarizationPrompt:()=>jl,generateToolCategoriesPrompt:()=>Ir,getContextWindowPercentage:()=>Cx,getDefaultSlmModel:()=>fc,getGlobalConfigDir:()=>Rl,getGlobalConfigPath:()=>Rr,getGlobalToolpackDir:()=>ox,getLocalConfigDir:()=>$l,getLocalConfigPath:()=>$r,getLocalToolpackDir:()=>nx,getMessageStats:()=>_x,getMimeType:()=>zs,getOllamaBaseUrl:()=>Mn,getOllamaProviderEntries:()=>mc,getRegisteredSlmModels:()=>hc,getRuntimeConfigStatus:()=>ek,getSafeOutputReserve:()=>Ns,getToolSearchSchema:()=>Qe,getToolpackConfig:()=>Wr,getUserHomeDir:()=>tx,gitAddTool:()=>zn,gitBlameTool:()=>Kn,gitBranchCreateTool:()=>Vn,gitBranchListTool:()=>Jn,gitCheckoutTool:()=>Qn,gitCloneTool:()=>Xn,gitCommitTool:()=>Hn,gitDiffTool:()=>Gn,gitLogTool:()=>Bn,gitStatusTool:()=>Un,gitToolsProject:()=>Ga,githubContentsGetTextTool:()=>$o,githubGraphqlExecuteTool:()=>Ro,githubIssuesCommentsCreateTool:()=>Io,githubPrDiffGetTool:()=>Mo,githubPrFilesListTool:()=>No,githubPrReviewCommentsReplyTool:()=>Ao,githubPrReviewThreadsListTool:()=>Eo,githubPrReviewThreadsResolveTool:()=>Do,githubPrReviewsSubmitTool:()=>Oo,githubToolsProject:()=>la,groupMessagesByRole:()=>Sx,handleContextWindowError:()=>fx,httpDeleteTool:()=>So,httpDownloadTool:()=>Po,httpGetTool:()=>vo,httpPostTool:()=>Co,httpPutTool:()=>ko,httpToolsProject:()=>Xi,initializeGlobalConfigIfFirstRun:()=>tk,isContextWindowError:()=>ux,isDataUri:()=>Hs,isRegisteredSlm:()=>gc,isToolSearchTool:()=>dt,k8sApplyManifestTool:()=>gr,k8sDeleteResourceTool:()=>hr,k8sDescribeTool:()=>ur,k8sGetConfigMapTool:()=>Tr,k8sGetLogsTool:()=>fr,k8sGetNamespacesTool:()=>xr,k8sListDeploymentsTool:()=>br,k8sListPodsTool:()=>dr,k8sListServicesTool:()=>yr,k8sSwitchContextTool:()=>wr,k8sToolsProject:()=>ll,k8sWaitForDeploymentTool:()=>vr,loadFullConfig:()=>pl,loadRuntimeConfig:()=>ZC,loadToolsConfig:()=>Ew,mergeSummarizationResults:()=>Ex,normalizeImagePart:()=>oc,ollamaRequest:()=>Re,ollamaStream:()=>Ur,parseDataUri:()=>Ks,parseFileEnvelope:()=>et,parseSkillFile:()=>rx,parseSummarizationResponse:()=>qs,prepareSummarizationRequest:()=>Fs,pruneMessages:()=>Is,raceAbort:()=>Fe,readFileAsBase64:()=>Js,reloadToolpackConfig:()=>pc,removeBypassRule:()=>uc,saveToolsConfig:()=>Dw,slackAuthTestTool:()=>fn,slackChatPostEphemeralTool:()=>pn,slackChatPostMessageTool:()=>cn,slackConversationsHistoryTool:()=>dn,slackConversationsRepliesTool:()=>un,slackReactionsAddTool:()=>mn,slackToolsProject:()=>il,systemCwdTool:()=>wo,systemDiskUsageTool:()=>xo,systemEnvTool:()=>bo,systemInfoTool:()=>yo,systemSetEnvTool:()=>To,systemToolsProject:()=>Bi,toDataUri:()=>tc,toolSearchDefinition:()=>We,truncateMessage:()=>kx,untilAborted:()=>vn,validateSummarizationResult:()=>js,webExtractLinksTool:()=>qo,webFeedTool:()=>Bo,webFetchTool:()=>Lo,webMapTool:()=>Wo,webMetadataTool:()=>Uo,webScrapeTool:()=>Fo,webScreenshotTool:()=>zo,webSearchTool:()=>jo,webSitemapTool:()=>Go,webToolsProject:()=>xa,wouldExceedContextWindow:()=>vx});module.exports=mx(nk);c();c();var dx={image:{maxBytes:10485760},document:{maxBytes:10485760,maxPages:20}};le();c();var Yl=require("events");le();c();le();c();le();var A=class extends M{constructor(e="The request was aborted"){super(e,"ABORTED"),this.name="AbortError"}};function Fe(r,e){return e?e.aborted?(r.catch(()=>{}),Promise.reject(new A)):new Promise((t,o)=>{let n=()=>{r.catch(()=>{}),o(new A)};e.addEventListener("abort",n,{once:!0}),r.then(s=>{e.removeEventListener("abort",n),t(s)},s=>{e.removeEventListener("abort",n),o(s)})}):r}async function*vn(r,e){if(!e){yield*r;return}let t=r[Symbol.asyncIterator](),o=!1;try{for(;;){let n=await Fe(t.next(),e);if(n.done){o=!0;return}yield n.value}}catch(n){if(n instanceof A)return;throw o=!0,n}finally{o||Promise.resolve(t.return?.()).catch(()=>{})}}function gx(r,e){return new Promise((t,o)=>{if(e?.aborted)return o(new A);let n=()=>{clearTimeout(s),o(new A)},s=setTimeout(()=>{e?.removeEventListener("abort",n),t()},r);e?.addEventListener("abort",n,{once:!0})})}async function Il(r,e={}){let{maxRetries:t=3,backoffMs:o=[1e4,3e4,6e4],isRetryable:n=a=>a instanceof ae,onRetry:s,signal:i}=e;for(let a=0;a<=t;a++){if(i?.aborted)throw new A;try{return await r()}catch(l){if(n(l)&&a<t){let p=l?.retryAfter!=null?l.retryAfter*1e3:o[a]??o[o.length-1]??6e4;s?.(a+1,p,l),await gx(p,i);continue}throw l}}throw new ae("Rate limit retries exhausted")}c();le();var Cn=class extends M{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 xn=class extends O{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 kn=class extends M{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 $s=null;async function dx(){if(!$s)try{$s=await import("js-tiktoken")}catch{}return $s}var Nl={"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},ux=2;async function fx(r,e){try{let t=await dx();if(!t)return Le(r);let o=t.encoding_for_model(e),n=0,s=Nl[e]??Nl.__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+=ux,n}catch{return Le(r)}}async function gx(r,e){try{let t=Le(r);return Math.ceil(t*1.1)}catch{return Le(r)}}async function hx(r,e){try{let t=Le(r);return Math.ceil(t*1.05)}catch{return Le(r)}}async function yx(r,e){let t=Le(r);return Math.ceil(t*1.05)}function Le(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 Es(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?fx(r,e):o==="anthropic"||o==="claude"?gx(r,e):o==="gemini"||o==="google"?hx(r,e):o==="ollama"?yx(r,e):Le(r)}function bx(r,e,t){let o=e-t;return r>o}function Tx(r,e){return Math.round(r/e*100)}function Ds(r,e=1.15){return Math.ceil(r*e)}l();function Ms(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=As(p);if(s+=d,n.push(p),p.role==="assistant"&&p.tool_calls?.length){let m=new Set(p.tool_calls.map(f=>f.id));for(let f of r)f.role==="tool"&&f.tool_call_id&&m.has(f.tool_call_id)&&(s+=As(f),n.push(f))}}let a=new Set(n),c=r.filter(p=>!a.has(p));return{removed:n.length,tokensReclaimed:s,newTotal:c.length,pruneInfo:{beforeCount:o,afterCount:c.length,removedMessages:n}}}function wx(r,e){if(typeof r.content=="string"){let t=e*4;if(r.content.length<=t)return r;let o=r.content.substring(0,t),n=Math.ceil((r.content.length-t)/4);return{...r,content:`${o}
348
+ ${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}};c();var As=null;async function hx(){if(!As)try{As=await import("js-tiktoken")}catch{}return As}var Ll={"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},yx=2;async function bx(r,e){try{let t=await hx();if(!t)return qe(r);let o=t.encoding_for_model(e),n=0,s=Ll[e]??Ll.__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+=yx,n}catch{return qe(r)}}async function Tx(r,e){try{let t=qe(r);return Math.ceil(t*1.1)}catch{return qe(r)}}async function wx(r,e){try{let t=qe(r);return Math.ceil(t*1.05)}catch{return qe(r)}}async function xx(r,e){let t=qe(r);return Math.ceil(t*1.05)}function qe(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 Ms(r,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?bx(r,e):o==="anthropic"||o==="claude"?Tx(r,e):o==="gemini"||o==="google"?wx(r,e):o==="ollama"?xx(r,e):qe(r)}function vx(r,e,t){let o=e-t;return r>o}function Cx(r,e){return Math.round(r/e*100)}function Ns(r,e=1.15){return Math.ceil(r*e)}c();function Is(r,e,t=!0){let o=r.length,n=[],s=0,i=[];r.forEach((p,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=Os(p);if(s+=d,n.push(p),p.role==="assistant"&&p.tool_calls?.length){let m=new Set(p.tool_calls.map(u=>u.id));for(let u of r)u.role==="tool"&&u.tool_call_id&&m.has(u.tool_call_id)&&(s+=Os(u),n.push(u))}}let a=new Set(n),l=r.filter(p=>!a.has(p));return{removed:n.length,tokensReclaimed:s,newTotal:l.length,pruneInfo:{beforeCount:o,afterCount:l.length,removedMessages:n}}}function kx(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 d=p.substring(0,c),m=Math.ceil((p.length-c)/4);i.push({type:"text",text:`${d}
350
+ [...truncated ${n} tokens]`}}else if(Array.isArray(r.content)){let t=r.content.filter(a=>a.type==="text"),o=t.reduce((a,l)=>a+(l.text?.length||0),0),n=e*4;if(o<=n)return r;let s=0,i=[];for(let a of t)if(a.type==="text"){let l=n-s;if(l<=0)break;let p=a.text;if(p.length<=l)i.push(a),s+=p.length;else{let d=p.substring(0,l),m=Math.ceil((p.length-l)/4);i.push({type:"text",text:`${d}
351
351
 
352
- [...truncated ${m} tokens]`});break}}return{...r,content:i.length>0?i:r.content}}return r}function As(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 xx(r){let e={system:[],user:[],assistant:[],tool:[]};return r.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function vx(r){let e=0,t={},o=0;for(let n of r){let s=As(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 Ns(r){return r.content==null?"":typeof r.content=="string"?r.content:r.content.map(e=>e.type==="text"?e.text:e.type==="image_url"?`[image: ${e.image_url.url}]`:e.type==="image_file"?`[image-file: ${e.image_file.path}]`:e.type==="image_data"?`[image-data: ${e.image_data.mimeType}]`:"").filter(Boolean).join(" ")}function Ol(r,e){if(e)return e;let t=r.filter(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 Os(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 Sx(r){let e={system:[],user:[],assistant:[],tool:[]};return r.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function _x(r){let e=0,t={},o=0;for(let n of r){let s=Os(n);e+=s,o=Math.max(o,s),t[n.role]??=0,t[n.role]++}return{totalMessages:r.length,totalTokens:e,byRole:t,largestMessageTokens:o}}c();le();function Ls(r){return r.content==null?"":typeof r.content=="string"?r.content:r.content.map(e=>e.type==="text"?e.text:e.type==="image_url"?`[image: ${e.image_url.url}]`:e.type==="image_file"?`[image-file: ${e.image_file.path}]`:e.type==="image_data"?`[image-data: ${e.image_data.mimeType}]`:"").filter(Boolean).join(" ")}function jl(r,e){if(e)return e;let t=r.filter(l=>l.role==="user"),o=r.filter(l=>l.role==="assistant"),n=r.filter(l=>l.role==="tool"),s=r.length,i=t.length,a=o.length;return`Please provide a concise summary of the following conversation history. The conversation contains ${s} messages (${i} user messages, ${a} assistant responses${n.length>0?`, and ${n.length} tool responses`:""}).
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 d=Ns(c);return`[Message ${p+1}] ${c.role.toUpperCase()}: ${d.substring(0,200)}${d.length>200?"...":""}`}).join(`
364
+ ${r.map((l,p)=>{let d=Ls(l);return`[Message ${p+1}] ${l.role.toUpperCase()}: ${d.substring(0,200)}${d.length>200?"...":""}`}).join(`
365
365
  `)}
366
366
  ---
367
367
 
368
- SUMMARY:`}function Dr(r,e){return{role:"system",content:`[Context Summary]
368
+ SUMMARY:`}function Nr(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 Cx(r){let e=new Set,t=[],o=[],n="";for(let s of r)if(s.role==="user"){let i=Ns(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=Ns(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 Il(r){return Math.ceil(r.length/4)}function Os(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 Is(r,e){let t=Ol(r,e.summaryPrompt);return[{role:"system",content:`You are a conversation summarizer. Your task is to create a clear, concise summary of the provided conversation that preserves all critical information.
375
+ Use this summary to understand the conversation context. When responding, acknowledge that you're aware of the previous conversation and continue naturally.`}}function Px(r){let e=new Set,t=[],o=[],n="";for(let s of r)if(s.role==="user"){let i=Ls(s);n=i,i.includes("?")&&o.push(i.split(`
376
+ `)[0]);let a=i.match(/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b/g);a&&a.forEach(l=>e.add(l))}else if(s.role==="assistant"){let i=Ls(s);if(i.includes("decided")||i.includes("concluded")||i.includes("determined")){let a=i.split(/[.!?]+/);for(let l of a)(l.includes("decided")||l.includes("concluded")||l.includes("determined"))&&t.push(l.trim())}}return{topics:Array.from(e).slice(0,10),decisions:t.slice(0,5),userGoals:o.slice(0,5),context:n.substring(0,200)}}function Fl(r){return Math.ceil(r.length/4)}function js(r){let e=[];return(!r.summary||r.summary.length<10)&&e.push("Summary is too short"),r.summary.length>5e3&&e.push("Summary is excessively long"),r.messageCount<2&&e.push("Must summarize at least 2 messages"),r.summaryTokens>=r.originalTokens*.8&&e.push("Summary is not significantly shorter than original messages"),r.tokensSaved<0&&e.push("Token calculation error: saved tokens is negative"),{valid:e.length===0,issues:e}}function Fs(r,e){let t=jl(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 js(r,e,t){let o=Il(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function kx(r,e,t){let o=[...r];return o.push(Dr(e.summary,e.messageCount)),o.push(...t),o}function Sx(r,e,t){let o=Math.round(r.tokensSaved/r.originalTokens*100);return`
379
+ Format: Write only the summary without any additional commentary.`},{role:"user",content:t}]}function qs(r,e,t){let o=Fl(r),n=Math.max(0,t-o);return{summary:r.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:n,timestamp:new Date}}function Rx(r,e,t){let o=[...r];return o.push(Nr(e.summary,e.messageCount)),o.push(...t),o}function $x(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 _x(r){if(r.length===0)throw new O("Cannot merge empty summarization results","CONTEXT_WINDOW_ERROR");return{summary:r.map(t=>`[Round ${r.indexOf(t)+1}] ${t.summary}`).join(`
398
+ `.trim()}function Ex(r){if(r.length===0)throw new M("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 Ar=class{states=new Map;config;maxTokens=1e5;constructor(e){this.config=e}getOrCreateState(e){return this.states.has(e)||this.states.set(e,{conversationId:e,estimatedTokens:0,lastUpdated:Date.now(),pruneCount:0,lastPrunedAt:void 0,warningsSent:0,summarizationCount:0}),this.states.get(e)}updateTokenCount(e,t){let o=this.getOrCreateState(e);return o.estimatedTokens=t,o.lastUpdated=Date.now(),o}recordPruneOperation(e,t){let o=this.getOrCreateState(e);return o.pruneCount++,o.lastPrunedAt=Date.now(),o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}recordWarning(e){let t=this.getOrCreateState(e);return t.warningsSent++,t.lastUpdated=Date.now(),t}recordSummarization(e,t){let o=this.getOrCreateState(e);return o.summarizationCount++,o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}getState(e){return this.states.get(e)}getAllStates(){return Array.from(this.states.values())}deleteState(e){return this.states.delete(e)}clearAllStates(){this.states.clear()}getStatistics(e){let t=this.states.get(e);if(!t)return null;let o=this.config.pruneThreshold||1e5,n=Math.round(t.estimatedTokens/o*100);return{conversationId:e,currentTokens:t.estimatedTokens,pruneCount:t.pruneCount,summarizationCount:t.summarizationCount,warningsSent:t.warningsSent,lastActivity:new Date(t.lastUpdated),contextWindowPercentage:n}}getExceedingThreshold(e){let t=e||this.maxTokens*(this.config.pruneThreshold||85)/100;return Array.from(this.states.values()).filter(o=>o.estimatedTokens>t)}getAtRiskConversations(e=80){let t=this.maxTokens,o=t*e/100;return Array.from(this.states.values()).filter(n=>n.estimatedTokens>o&&n.estimatedTokens<=t)}generateReport(){let e=this.getAllStates();if(e.length===0)return"No conversations tracked yet.";let t=this.config.pruneThreshold||1e5,o=["Context Window State Report","==========================",`Report Generated: ${new Date().toISOString()}`,`Context Window Limit: ${t} tokens`,`Total Conversations: ${e.length}`,""],n=e.reduce((m,f)=>m+f.estimatedTokens,0),s=e.reduce((m,f)=>m+f.pruneCount,0),i=e.reduce((m,f)=>m+f.summarizationCount,0),a=Math.round(n/e.length);o.push("Summary:"),o.push(`- Total tokens across all conversations: ${n}`),o.push(`- Average tokens per conversation: ${a}`),o.push(`- Total prune operations: ${s}`),o.push(`- Total summarizations: ${i}`),o.push("");let c=this.getAtRiskConversations();c.length>0&&(o.push(`At-Risk Conversations (80%+ threshold): ${c.length}`),c.forEach(m=>{let f=Math.round(m.estimatedTokens/t*100);o.push(`- ${m.conversationId}: ${m.estimatedTokens}/${t} tokens (${f}%)`)}),o.push(""));let p=this.getExceedingThreshold();return p.length>0&&(o.push(`Exceeded Conversations: ${p.length}`),p.forEach(m=>{let f=m.estimatedTokens-t;o.push(`- ${m.conversationId}: ${m.estimatedTokens}/${t} tokens (+${f} over)`)}),o.push("")),o.push("Most Active Conversations (by operations):"),[...e].sort((m,f)=>{let b=m.pruneCount+m.summarizationCount;return f.pruneCount+f.summarizationCount-b}).slice(0,5).forEach(m=>{let f=m.pruneCount+m.summarizationCount;o.push(`- ${m.conversationId}: ${m.pruneCount} prunes, ${m.summarizationCount} summarizations (${f} operations)`)}),o.join(`
401
- `)}export(){let e={};for(let[t,o]of this.states.entries())e[t]={...o,lastUpdated:o.lastUpdated,lastPrunedAt:o.lastPrunedAt};return e}import(e){for(let[t,o]of Object.entries(e))this.states.set(t,{...o,lastUpdated:typeof o.lastUpdated=="number"?o.lastUpdated:new Date(o.lastUpdated).getTime(),lastPrunedAt:o.lastPrunedAt&&typeof o.lastPrunedAt!="number"?new Date(o.lastPrunedAt).getTime():o.lastPrunedAt})}pruneInactiveConversations(e=60){let t=Date.now()-e*60*1e3,o=[];for(let[n,s]of this.states.entries())s.lastUpdated<t&&o.push(n);return o.forEach(n=>this.states.delete(n)),o}getMemoryUsage(){let e=this.states.size,t=e*500;return{conversationCount:e,approximateByteSize:t}}validateIntegrity(){let e=[];for(let[t,o]of this.states.entries())(!t||typeof t!="string")&&e.push(`Invalid conversation ID: ${t}`),o.estimatedTokens<0&&e.push(`Negative token count for ${t}: ${o.estimatedTokens}`),o.pruneCount<0&&e.push(`Negative prune count for ${t}: ${o.pruneCount}`),o.summarizationCount<0&&e.push(`Negative summarization count for ${t}: ${o.summarizationCount}`),o.warningsSent<0&&e.push(`Negative warning count for ${t}: ${o.warningsSent}`),(typeof o.lastUpdated!="number"||o.lastUpdated<=0)&&e.push(`Invalid lastUpdated timestamp for ${t}`),o.lastPrunedAt!==void 0&&(typeof o.lastPrunedAt!="number"||o.lastPrunedAt<=0)&&e.push(`Invalid lastPrunedAt timestamp for ${t}`);return{isValid:e.length===0,issues:e}}};function Ls(r){return new Ar(r)}l();vn();var Dt=class{discoveryCache=new ct;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(Je(i.length?i:void 0)),s.add(Ke);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=ct.fromMessages(e);this.discoveryCache.merge(p);let d=this.discoveryCache.getDiscoveredTools();for(let m of d){let f=t.get(m);f&&!s.has(m)&&f.cacheable!==!1&&(n.push(this.toSchema(f)),s.add(m))}}return n}resolveLegacy(e,t){let o;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)o=e.getEnabled();else{let n=e.getByNames(t.enabledTools),s=e.getByCategories(t.enabledToolCategories),i=new Set;o=[];for(let a of[...n,...s])i.has(a.name)||(i.add(a.name),o.push(a))}return o.map(n=>this.toSchema(n))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};l();var Wl={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},te={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:Wl};vn();l();function Ul(r){if(r.disabled)return"";let e=r.includeWorkingDirectory!==!1,t=r.includeToolCategories!==!1,o=e?`
400
+ `),messageCount:r.reduce((t,o)=>t+o.messageCount,0),originalTokens:r.reduce((t,o)=>t+o.originalTokens,0),summaryTokens:r.reduce((t,o)=>t+o.summaryTokens,0),tokensSaved:r.reduce((t,o)=>t+o.tokensSaved,0),timestamp:new Date}}c();var Or=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,u)=>m+u.estimatedTokens,0),s=e.reduce((m,u)=>m+u.pruneCount,0),i=e.reduce((m,u)=>m+u.summarizationCount,0),a=Math.round(n/e.length);o.push("Summary:"),o.push(`- Total tokens across all conversations: ${n}`),o.push(`- Average tokens per conversation: ${a}`),o.push(`- Total prune operations: ${s}`),o.push(`- Total summarizations: ${i}`),o.push("");let l=this.getAtRiskConversations();l.length>0&&(o.push(`At-Risk Conversations (80%+ threshold): ${l.length}`),l.forEach(m=>{let u=Math.round(m.estimatedTokens/t*100);o.push(`- ${m.conversationId}: ${m.estimatedTokens}/${t} tokens (${u}%)`)}),o.push(""));let p=this.getExceedingThreshold();return p.length>0&&(o.push(`Exceeded Conversations: ${p.length}`),p.forEach(m=>{let u=m.estimatedTokens-t;o.push(`- ${m.conversationId}: ${m.estimatedTokens}/${t} tokens (+${u} over)`)}),o.push("")),o.push("Most Active Conversations (by operations):"),[...e].sort((m,u)=>{let b=m.pruneCount+m.summarizationCount;return u.pruneCount+u.summarizationCount-b}).slice(0,5).forEach(m=>{let u=m.pruneCount+m.summarizationCount;o.push(`- ${m.conversationId}: ${m.pruneCount} prunes, ${m.summarizationCount} summarizations (${u} operations)`)}),o.join(`
401
+ `)}export(){let e={};for(let[t,o]of this.states.entries())e[t]={...o,lastUpdated:o.lastUpdated,lastPrunedAt:o.lastPrunedAt};return e}import(e){for(let[t,o]of Object.entries(e))this.states.set(t,{...o,lastUpdated:typeof o.lastUpdated=="number"?o.lastUpdated:new Date(o.lastUpdated).getTime(),lastPrunedAt:o.lastPrunedAt&&typeof o.lastPrunedAt!="number"?new Date(o.lastPrunedAt).getTime():o.lastPrunedAt})}pruneInactiveConversations(e=60){let t=Date.now()-e*60*1e3,o=[];for(let[n,s]of this.states.entries())s.lastUpdated<t&&o.push(n);return o.forEach(n=>this.states.delete(n)),o}getMemoryUsage(){let e=this.states.size,t=e*500;return{conversationCount:e,approximateByteSize:t}}validateIntegrity(){let e=[];for(let[t,o]of this.states.entries())(!t||typeof t!="string")&&e.push(`Invalid conversation ID: ${t}`),o.estimatedTokens<0&&e.push(`Negative token count for ${t}: ${o.estimatedTokens}`),o.pruneCount<0&&e.push(`Negative prune count for ${t}: ${o.pruneCount}`),o.summarizationCount<0&&e.push(`Negative summarization count for ${t}: ${o.summarizationCount}`),o.warningsSent<0&&e.push(`Negative warning count for ${t}: ${o.warningsSent}`),(typeof o.lastUpdated!="number"||o.lastUpdated<=0)&&e.push(`Invalid lastUpdated timestamp for ${t}`),o.lastPrunedAt!==void 0&&(typeof o.lastPrunedAt!="number"||o.lastPrunedAt<=0)&&e.push(`Invalid lastPrunedAt timestamp for ${t}`);return{isValid:e.length===0,issues:e}}};function Ws(r){return new Or(r)}c();Sn();var Mt=class{discoveryCache=new mt;async resolve(e,t,o){return o.enabled?o.toolSearch?.enabled?this.resolveWithToolSearch(e,t,o):this.resolveLegacy(t,o):[]}getDiscoveryCache(){return this.discoveryCache}clearDiscoveryCache(){this.discoveryCache.clear()}resolveWithToolSearch(e,t,o){let n=[],s=new Set,i=t.getCategories().filter(p=>p!=="meta");n.push(Qe(i.length?i:void 0)),s.add(Ve);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 l=o.toolSearch?.alwaysLoadedCategories??[];for(let p of l)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=mt.fromMessages(e);this.discoveryCache.merge(p);let d=this.discoveryCache.getDiscoveredTools();for(let m of d){let u=t.get(m);u&&!s.has(m)&&u.cacheable!==!1&&(n.push(this.toSchema(u)),s.add(m))}}return n}resolveLegacy(e,t){let o;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)o=e.getEnabled();else{let n=e.getByNames(t.enabledTools),s=e.getByCategories(t.enabledToolCategories),i=new Set;o=[];for(let a of[...n,...s])i.has(a.name)||(i.add(a.name),o.push(a))}return o.map(n=>this.toSchema(n))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};c();var Bl={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},oe={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:Bl};Sn();c();function zl(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 At=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 Nr=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let n=e[o],s=[],i=JSON.stringify(n.arguments).toLowerCase();for(let a=0;a<o;a++){let c=e[a];this.hasDependency(n,c,i)&&s.push(c.id)}t.push({toolCallId:n.id,dependsOn:s})}return t}hasDependency(e,t,o){if(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&o.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&o.includes(t.arguments.url.toLowerCase()))return!0;let s=["github.pr.files.list","github.pr.diff.get","github.contents.getText"];if(["github.pr.reviews.submit","github.pr.reviewComments.reply"].includes(e.name)&&s.includes(t.name)||e.name==="github.contents.getText"&&t.name==="github.pr.files.list"||e.name==="github.pr.reviewThreads.resolve"&&t.name==="github.pr.reviewThreads.list")return!0;let a=["slack.conversations.history","slack.conversations.replies"];return!!(["slack.chat.postMessage","slack.chat.postEphemeral"].includes(e.name)&&a.includes(t.name)||e.name==="slack.reactions.add"&&a.includes(t.name))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let n=this.analyzeDependencies(e),s=new Map,i=new Set;for(;i.size<e.length;){let a=[];for(let p of e){if(i.has(p.id))continue;(n.find(f=>f.toolCallId===p.id)?.dependsOn.every(f=>i.has(f))??!0)&&a.push(p)}if(a.length===0){let p=e.filter(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 mt(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();var Or=require("fs/promises"),Xe=require("path");l();function Hl(r){return r.trim()}var $x=".toolpack/rules",Ex=3e4,ft=class{constructor(e=Ex){this.cacheTtlMs=e}cacheTtlMs;modeCache=new Map;async loadForMode(e,t){let o=t??$x,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((0,Xe.join)(o,"__global__"),i),e&&await this.collectFromFolder((0,Xe.join)(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 f=Hl(m);f&&c.push(f)}let p=c.length===0?"":`<rules>
410
- ${c.join(`
408
+ - Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}c();var Nt=class{analyticalPatterns=[/\b(analyze|find|search|check|list|show)\b/i,/\b(biggest|largest|smallest|most|least|all|every|count)\b/i,/\b(explain|understand|review|audit|inspect|examine)\b/i,/\b(compare|difference|similar|match|pattern)\b/i,/\b(what|where|how many|which|who|when|why|how)\b/i,/\?$/];actionPatterns=[/\b(create|write|update|modify|edit|patch|delete|remove|rename|move|copy)\b/i,/\b(run|execute|start|stop|restart|deploy|install|build)\b/i,/\b(fix|refactor|implement|add|change|replace|insert)\b/i,/\b(make|do|set|configure|setup|initialize)\b/i];classify(e){if(!e||e.trim().length===0)return{type:"conversational",confidence:0};let t=e.toLowerCase(),o=this.analyticalPatterns.filter(a=>a.test(t)).length,n=this.actionPatterns.filter(a=>a.test(t)).length,s=o/this.analyticalPatterns.length,i=n/this.actionPatterns.length;if(o>n&&o>0){let a=Math.min(s,1);return n>0&&(a=Math.min(a,.5)),{type:"analytical",confidence:a,reasoning:`Matched ${o} analytical patterns${n>0?`, ${n} action patterns (capped confidence)`:""}`}}else return n>o&&n>0?{type:"action",confidence:Math.min(i,1),reasoning:`Matched ${n} action patterns`}:o===n&&o>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${o} analytical, ${n} action patterns)`}:{type:"conversational",confidence:.3,reasoning:"No strong analytical or action patterns detected"}}getToolRoundsAdjustment(e,t){return e.type==="analytical"&&e.confidence>.6?Math.min(t+3,10):(e.type==="action"&&e.confidence>.6,t)}};c();var Lr=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let n=e[o],s=[],i=JSON.stringify(n.arguments).toLowerCase();for(let a=0;a<o;a++){let l=e[a];this.hasDependency(n,l,i)&&s.push(l.id)}t.push({toolCallId:n.id,dependsOn:s})}return t}hasDependency(e,t,o){if(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&o.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&o.includes(t.arguments.url.toLowerCase()))return!0;let s=["github.pr.files.list","github.pr.diff.get","github.contents.getText"];if(["github.pr.reviews.submit","github.pr.reviewComments.reply"].includes(e.name)&&s.includes(t.name)||e.name==="github.contents.getText"&&t.name==="github.pr.files.list"||e.name==="github.pr.reviewThreads.resolve"&&t.name==="github.pr.reviewThreads.list")return!0;let a=["slack.conversations.history","slack.conversations.replies"];return!!(["slack.chat.postMessage","slack.chat.postEphemeral"].includes(e.name)&&a.includes(t.name)||e.name==="slack.reactions.add"&&a.includes(t.name))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let n=this.analyzeDependencies(e),s=new Map,i=new Set;for(;i.size<e.length;){let a=[];for(let p of e){if(i.has(p.id))continue;(n.find(u=>u.toolCallId===p.id)?.dependsOn.every(u=>i.has(u))??!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 l=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:d}of l)s.set(p,d),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let n=async i=>(await Promise.allSettled(i.map(async l=>({id:l.id,result:await t(l)})))).map((l,p)=>l.status==="fulfilled"?l.value:{id:i[p].id,result:JSON.stringify({error:l.reason?.message??"Tool execution failed"})});if(e.length<=o)return n(e);let s=[];for(let i=0;i<e.length;i+=o)s.push(...await n(e.slice(i,i+o)));return s}shouldUseParallelExecution(e){return e.length>=2}};c();function ut(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""}P();c();c();var jr=require("fs/promises"),Ze=require("path");c();function Vl(r){return r.trim()}var Mx=".toolpack/rules",Nx=3e4,ht=class{constructor(e=Nx){this.cacheTtlMs=e}cacheTtlMs;modeCache=new Map;async loadForMode(e,t){let o=t??Mx,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((0,Ze.join)(o,"__global__"),i),e&&await this.collectFromFolder((0,Ze.join)(o,e),i),i.size===0)return this.modeCache.set(n,{value:"",cachedAt:Date.now()}),"";let a=new Map,l=[];for(let d of i){let m=await this.readFile(d,a);if(!m)continue;let u=Vl(m);u&&l.push(u)}let p=l.length===0?"":`<rules>
410
+ ${l.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=(0,Xe.resolve)(e);try{await this.collectRecursive(o,t)}catch{}}async collectRecursive(e,t){let o=await(0,Or.readdir)(e,{withFileTypes:!0});for(let n of o){let s=(0,Xe.join)(e,n.name);n.isDirectory()?await this.collectRecursive(s,t):n.isFile()&&(0,Xe.extname)(n.name)===".md"&&t.add(s)}}async readFile(e,t){if(t.has(e))return t.get(e);try{let o=await(0,Or.readFile)(e,"utf-8");return t.set(e,o),o}catch{return""}}};function Ir(r,e){ut("debug")&&(y(`[AIClient][${r}] Messages (${e.length}):`),e.forEach((t,o)=>{let n=t,s=typeof n.content=="string"?n.content:A(n.content,1e4);y(`[AIClient][${r}] #${o} role=${n.role} content=${s}`)}))}function Kl(r){let e=mt(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 Jl(r){let e=mt(r).toLowerCase();if(!e)return!1;let t=[/\b(list|show|print|display)\b.*\b(files|folders|directory|dir)\b/,/\b(current|this)\b.*\b(directory|folder|repo|repository)\b/,/\b(read|open|view)\b.*\b(file|log|config|json|yaml|env)\b/],o=[/\b(write|create|update|modify|edit|patch|delete|remove|rename|move|copy)\b/,/\b(run|execute)\b.*\b(command|shell|script|tests?)\b/,/\b(http|get|post|put|delete|download|fetch|curl)\b/,/\b(web|search|scrape|crawl)\b/];return t.some(n=>n.test(e))&&!o.some(n=>n.test(e))}var kn=class extends Vl.EventEmitter{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||te,this.toolRouter=new Dt,this.bm25Engine=new Et,this.queryClassifier=new At,this.toolOrchestrator=new Nr,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1,this.disableToolGuidance=e.disableToolGuidance||!1;let t=this.toolsConfig.resultMaxChars??te.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.hitlConfig=e.hitlConfig,this.onToolConfirm=e.onToolConfirm,this.conversationId=e.conversationId,this.contextWindowConfig=e.contextWindowConfig,this.actor=e.actor,this.providerModelCache=new Map,this.ruleLoader=new ft,this.contextWindowConfig&&this.contextWindowConfig.enabled!==!1&&(this.contextWindowStateManager=Ls(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:Es(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=Ms(s.messages,c,n),d=new Set(p.pruneInfo.removedMessages),m=s.messages.filter(h=>!d.has(h)),f={...s,messages:m};if(this.contextWindowStateManager&&this.contextWindowStateManager.recordPruneOperation(this.getConversationId(),p.tokensReclaimed),await this.countRequestTokens(f,t,f.model)<=o||m.length===s.messages.length)return f;s=f}return e}async pruneToMaxMessageHistory(e){let t=this.contextWindowConfig?.maxMessageHistoryLength;if(!t||e.messages.length<=t)return e;let o=this.contextWindowConfig?.retainSystemMessages??!0,n=[];e.messages.forEach((c,p)=>{o&&c.role==="system"||c.role!=="tool"&&n.push(p)});let s=Math.max(0,e.messages.length-t);if(s===0)return e;let i=new Set(n.slice(0,s)),a=e.messages.filter((c,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,n=o.filter(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=Is(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 xn("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let m=await this.countRequestTokens({...e,messages:a},t,c),f=js(d.content,a,m),b=Os(f);if(!b.valid)throw new xn(`Summarization result is invalid: ${b.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",d.content);let h=Dr(f.summary,a.length),T=[...n,h,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),f.tokensSaved),{...e,messages:T}}async enforceContextWindow(e,t){if(!this.contextWindowConfig||this.contextWindowConfig.enabled===!1)return e;let o=await this.pruneToMaxMessageHistory(e),n=await this.getModelInfo(t,o.model),s=n?.contextWindow??1e5,i=o.max_tokens??n?.maxOutputTokens??1024,a=this.contextWindowConfig.outputTokenBuffer??1.15,c=Ds(i,a),p=Math.max(0,s-c),d=Math.floor(s*((this.contextWindowConfig.pruneThreshold??85)/100)),m=Math.min(p,d),f=await this.countRequestTokens(o,t,o.model);if(this.contextWindowStateManager&&(this.contextWindowStateManager.updateTokenCount(this.getConversationId(),f),f>m&&this.contextWindowStateManager.recordWarning(this.getConversationId())),f<=m)return o;let b=this.contextWindowConfig.strategy??"prune";if(b==="fail"&&f>p)throw new wn("Context window exceeded by request messages",this.getConversationId(),f,p,b);if(b==="summarize")try{let T=await this.summarizeConversation(o,t);if(await this.countRequestTokens(T,t,T.model)<=p)return T;o=await this.pruneConversation(T,t,p)}catch{o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let h=await this.countRequestTokens(o,t,o.model);if(h>p&&b==="fail")throw new wn("Context window exceeded after attempted cleanup",this.getConversationId(),h,p,b);return o}isBypassed(e){let t=this.hitlConfig;if(!t||t.enabled===!1)return!0;let o=t.confirmationMode??"all";if(o==="off"||o==="high-only"&&e.confirmation?.level==="medium")return!0;let n=t.bypass??{};return!!(n.tools?.includes(e.name)||n.categories?.includes(e.category)||e.confirmation&&n.levels?.includes(e.confirmation.level))}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new O("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new O(`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 O(`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,f=d.requestToolMap;m=await this.enforceContextWindow(m,n);let b=a.toolChoicePolicy||process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||"auto",h=(m.tools?.length||0)>0,T=m.tool_choice!=null,k=Kl(m.messages),C=Jl(m.messages);!T&&h&&(b==="required"||b==="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=${b} needsTools=${k} autoExecute=${a.enabled&&a.autoExecute}`),Ws(s,m.tools),Ir(s,m.messages);let j=ne=>Ml(()=>n.generate(ne),{onRetry:(B,Z)=>S(`[AIClient][${s}] Rate limited \u2014 retrying in ${Z/1e3}s (attempt ${B}/3)`)}),R=await j(E);if(y(`[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||f.size>0||(i?.customTools?.length??0)>0)){let ne=mt(m.messages),B=this.queryClassifier.classify(ne),Z=a.maxToolRounds,we=m.maxToolRounds!==void 0?m.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(B,Z);m.maxToolRounds!==void 0?y(`[AIClient][${s}] maxToolRounds overridden per-request: ${we} (classifier bypassed)`):we!==Z?S(`[AIClient][${s}] Query classified as ${B.type} (confidence: ${B.confidence.toFixed(2)}), adjusted maxToolRounds: ${Z} \u2192 ${we}`):y(`[AIClient][${s}] Query classified as ${B.type} (confidence: ${B.confidence.toFixed(2)}), keeping maxToolRounds: ${we}`);let le=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&&le<we;){if(e.signal?.aborted){S(`[AIClient][${s}] generate() aborted by signal`);break}le++,S(`[AIClient][${s}] generate() tool round ${le}/${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,De=R.tool_calls,Ge=R.tool_calls.filter(U=>U.name==="web.fetch");if(Ge.length>V){S(`[AIClient][${s}] Limiting web.fetch calls from ${Ge.length} \u2192 ${V} to prevent context overflow`);let U=Ge.slice(0,V);De=[...R.tool_calls.filter(ye=>ye.name!=="web.fetch"),...U];let H=Ge.slice(V);for(let ye of H)J.push({role:"tool",tool_call_id:ye.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let ce=5e4,he=0;if(z){S(`[AIClient][${s}] Using parallel execution for ${De.length} tools`);let U;try{U=await this.toolOrchestrator.executeWithDependencies(De,D=>this.executeTool(D,f,i,le),5)}catch(D){fe(`[AIClient][${s}] Parallel tool execution failed: ${D.message}`),U=new Map(De.map(H=>[H.id,JSON.stringify({error:D.message??"Tool execution failed"})]))}for(let D of De){let H=U.get(D.id)??JSON.stringify({error:"Tool execution result missing"}),ye=typeof H=="string"?H:JSON.stringify(H),Rt=ce-he,re=ye.startsWith("data:image/"),se;re?se=ye:he+ye.length>ce?(N(`[AIClient][${s}] Tool output budget exceeded (${ce} chars)`),se=this.budgetTruncate(ye,Rt)):typeof H=="string"&&H.length>this.toolResultMaxChars?se=`${H.slice(0,this.toolResultMaxChars)}
414
- [TRUNCATED tool result: ${H.length} chars]`:se=ye;let $=typeof se=="string"?se:JSON.stringify(se);re||(he+=$.length),J.push({role:"tool",tool_call_id:D.id,content:se})}y(`[AIClient][${s}] Round tool output size: ${he} chars (budget: ${ce})`)}else{S(`[AIClient][${s}] Using sequential execution for ${De.length} tools`);for(let U of De){let D;try{D=await this.executeTool(U,f,i,le)}catch($){D=JSON.stringify({error:$.message??"Tool execution failed"})}let H=typeof D=="string"?D:JSON.stringify(D),ye=ce-he,Rt=H.startsWith("data:image/"),re;Rt?re=H:he+H.length>ce?(N(`[AIClient][${s}] Tool output budget exceeded (${ce} chars)`),re=this.budgetTruncate(H,ye)):typeof D=="string"&&D.length>this.toolResultMaxChars?re=`${D.slice(0,this.toolResultMaxChars)}
415
- [TRUNCATED tool result: ${D.length} chars]`:re=H;let se=typeof re=="string"?re:JSON.stringify(re);Rt||(he+=se.length),J.push({role:"tool",tool_call_id:U.id,content:re})}y(`[AIClient][${s}] Round tool output size: ${he} chars (budget: ${ce})`)}let je={...m,messages:J,__toolpack_request_id:s,...P?{response_format:P}:{}},Be=o?.getLatestRequestTools?.()??[];if(Be.length>0){let U=new Map((m.requestTools??[]).map(D=>[D.name,D]));for(let D of Be)U.set(D.name,D);je.requestTools=Array.from(U.values());for(let D of Be)f.set(D.name,D)}let Se=this.stripRequestTools((await this.enrichRequestWithTools(je,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}`)),ut("debug")&&(y(`[AIClient][${s}] generate() followup request messages=${J.length}`),Ir(s,J)),R=await j(Se),y(`[AIClient][${s}] generate() followup response finish_reason=${R.finish_reason??"unknown"} tool_calls=${R.tool_calls?.length||0} content=${R.content||""}`)}if(le>=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){N(`[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,f=d.requestToolMap;m=await this.enforceContextWindow(m,n);let b=c.toolChoicePolicy||process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||"auto",h=(m.tools?.length||0)>0,T=m.tool_choice!=null,k=Kl(m.messages),C=Jl(m.messages);!T&&h&&(b==="required"||b==="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=${b} needsTools=${k} autoExecute=${c.enabled&&c.autoExecute}`),Ws(s,m.tools),Ir(s,m.messages),!c.autoExecute||!this.toolRegistry&&f.size===0&&(a?.customTools?.length??0)===0){yield*n.stream(E);return}let j=[...m.messages],R=0,ne=!1,B=mt(m.messages),Z=this.queryClassifier.classify(B),we=c.maxToolRounds,le=m.maxToolRounds!==void 0?m.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(Z,we);for(m.maxToolRounds!==void 0?y(`[AIClient][${s}] stream() maxToolRounds overridden per-request: ${le} (classifier bypassed)`):le!==we&&S(`[AIClient][${s}] stream() Query classified as ${Z.type} (confidence: ${Z.confidence.toFixed(2)}), adjusted maxToolRounds: ${we} \u2192 ${le}`);R<=le;){if(e.signal?.aborted){S(`[AIClient][${s}] stream() aborted by signal`);return}let J="",z=[];R++,S(`[AIClient][${s}] stream() round_start ${R}/${le}`);let V=null,De={...m,messages:j,...P?{response_format:P}:{}},Ge=o?.getLatestRequestTools?.()??[];if(Ge.length>0){let $=new Map((m.requestTools??[]).map(F=>[F.name,F]));for(let F of Ge)$.set(F.name,F);De.requestTools=Array.from($.values());for(let F of Ge)f.set(F.name,F)}let ce=this.stripRequestTools((await this.enrichRequestWithTools(De,a)).request);ce=await this.enforceContextWindow(ce,n),R>1&&ce.tool_choice==="required"&&(ce.tool_choice=C?"none":"auto",S(`[AIClient][${s}] stream() round_${R} tool_choice override required->${ce.tool_choice}`));for await(let $ of n.stream(ce)){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),y(`[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(y(`[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}/${le}`),j.push({role:"assistant",content:J||"",tool_calls:z.map($=>({id:$.id,type:"function",function:{name:$.name,arguments:JSON.stringify($.arguments)}}))});let he=3,je=z,Be=z.filter($=>$.name==="web.fetch");if(Be.length>he){S(`[AIClient][${s}] Limiting web.fetch calls from ${Be.length} \u2192 ${he} to prevent context overflow`);let $=Be.slice(0,he);je=[...z.filter(Tn=>Tn.name!=="web.fetch"),...$];let _e=Be.slice(he);for(let Tn of _e)j.push({role:"tool",tool_call_id:Tn.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let Se=5e4,U=0,D=[],H=!1,ye=setInterval(()=>{H||D.push({delta:""})},500),Rt=Date.now(),re,se;try{if(je.length>=2)S(`[AIClient][${s}] stream() using parallel execution for ${je.length} tools`),se=new Map,re=await this.toolOrchestrator.executeWithDependencies(je,async $=>{let F=Date.now(),_e=await this.executeTool($,f,a,R);return se.set($.id,Date.now()-F),_e},5);else{S(`[AIClient][${s}] stream() executing single tool sequentially`),se=new Map,re=new Map;for(let $ of je){let F=Date.now(),_e=await this.executeTool($,f,a,R);se.set($.id,Date.now()-F),re.set($.id,_e)}}}finally{H=!0,clearInterval(ye)}for(;D.length>0;)yield D.shift();await new Promise($=>setTimeout($,0)),y(`[AIClient][${s}] stream() tool batch completed in ${Date.now()-Rt}ms`);for(let $ of je){let F=re.get($.id),_e=typeof F=="string"?F:JSON.stringify(F),Tn=Se-U,ox=se.get($.id)??0,El=_e.startsWith("data:image/"),ze;El?ze=_e:U+_e.length>Se?(N(`[AIClient][${s}] Tool output budget exceeded (${Se} chars)`),ze=this.budgetTruncate(_e,Tn)):typeof F=="string"&&F.length>this.toolResultMaxChars?ze=`${F.slice(0,this.toolResultMaxChars)}
416
- [TRUNCATED tool result: ${F.length} chars]`:ze=_e;let Dl=typeof ze=="string"?ze:JSON.stringify(ze);El||(U+=Dl.length),j.push({role:"tool",tool_call_id:$.id,content:ze}),yield{delta:"",tool_calls:[{...$,result:Dl,duration:ox}]}}y(`[AIClient][${s}] Round tool output size: ${U} chars (budget: ${Se})`),ut("debug")&&(y(`[AIClient][${s}] stream() after_tools messages=${j.length}`),Ir(s,j)),R>le&&(ne=!0)}if(ne&&!e.signal?.aborted){S(`[AIClient][${s}] Tool-round cap (${le}) 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){N(`[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(h=>this.requestToolToSchema(h)),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 w=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(c)),v=w===e.tools?e:{...e,tools:w};return{request:this.injectRequestToolGuidance(v,w),requestToolMap:o}}let h=await this.toolRouter.resolve(e.messages,this.toolRegistry,p);if(y(`[AIClient] Resolved ${h.length} tools to send: ${h.map(w=>w.name).join(", ")||"none"}`),t&&h.length>0){let w=h.length;h=this.filterSchemasByMode(h,t);let v=w-h.length;v>0&&S(`[AIClient] Mode "${t.displayName}" filtered out ${v} tools`)}let T=new Set(e.tools.map(w=>w.function.name)),k=h.filter(w=>!T.has(w.name)).map(w=>({type:"function",function:{name:w.name,description:w.description,parameters:w.parameters}}));if(k.length===0){y(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`);let w=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(c)),v=w===e.tools?e:{...e,tools:w};return{request:this.injectRequestToolGuidance(v,w),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){y("[AIClient] Tool registry not configured, skipping tool resolution");let h=this.schemasToToolCallRequests(c),T=h.length>0?{...e,tools:h}:e;return{request:this.injectRequestToolGuidance(T,h),requestToolMap:o}}let d=this.toolRegistry,m=await this.toolRouter.resolve(e.messages,d,p);if(y(`[AIClient] Resolved ${m.length} tools to send: ${m.map(h=>h.name).join(", ")||"none"}`),t&&m.length>0){let h=m.length;m=this.filterSchemasByMode(m,t);let T=h-m.length;T>0&&S(`[AIClient] Mode "${t.displayName}" filtered out ${T} tools`)}let f=this.schemasToToolCallRequests(this.mergeSchemas(m,c));if(f.length===0)return{request:e,requestToolMap:o};let b={...e,tools:f};return i.toolSearch?.enabled&&d&&(b=this.injectToolSearchPrompt(b)),{request:this.injectRequestToolGuidance(b,f),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(`
413
+ </rules>`;return this.modeCache.set(n,{value:p,cachedAt:Date.now()}),p}clearCache(){this.modeCache.clear()}async collectFromFolder(e,t){let o=(0,Ze.resolve)(e);try{await this.collectRecursive(o,t)}catch{}}async collectRecursive(e,t){let o=await(0,jr.readdir)(e,{withFileTypes:!0});for(let n of o){let s=(0,Ze.join)(e,n.name);n.isDirectory()?await this.collectRecursive(s,t):n.isFile()&&(0,Ze.extname)(n.name)===".md"&&t.add(s)}}async readFile(e,t){if(t.has(e))return t.get(e);try{let o=await(0,jr.readFile)(e,"utf-8");return t.set(e,o),o}catch{return""}}};function Fr(r,e){gt("debug")&&(y(`[AIClient][${r}] Messages (${e.length}):`),e.forEach((t,o)=>{let n=t,s=typeof n.content=="string"?n.content:N(n.content,1e4);y(`[AIClient][${r}] #${o} role=${n.role} content=${s}`)}))}function Ql(r){let e=ut(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 Xl(r){let e=ut(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 Pn=class extends Yl.EventEmitter{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||oe,this.toolRouter=new Mt,this.bm25Engine=new At,this.queryClassifier=new Nt,this.toolOrchestrator=new Lr,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1,this.disableToolGuidance=e.disableToolGuidance||!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.actor=e.actor,this.providerModelCache=new Map,this.ruleLoader=new ht,this.contextWindowConfig&&this.contextWindowConfig.enabled!==!1&&(this.contextWindowStateManager=Ws(this.contextWindowConfig)),this.toolRegistry&&this.bm25Engine.index(this.toolRegistry.getAll())}getConversationId(){return this.conversationId||"global"}async getModelInfo(e,t){let o=e.name||e.constructor.name,n=this.providerModelCache.get(o);if(!n){try{n=await e.getModels()}catch{n=[]}this.providerModelCache.set(o,n)}return n.find(s=>s.id===t||s.displayName===t)}async countRequestTokens(e,t,o){let n=await t.countTokens(e.messages,o);return typeof n=="number"&&Number.isFinite(n)?n:Ms(e.messages,o,t.getDisplayName().toLowerCase())}async pruneConversation(e,t,o){let n=this.contextWindowConfig?.retainSystemMessages??!0,s=e;for(let i=0;i<3;i+=1){let a=await this.countRequestTokens(s,t,s.model);if(a<=o)return s;let l=a-o,p=Is(s.messages,l,n),d=new Set(p.pruneInfo.removedMessages),m=s.messages.filter(h=>!d.has(h)),u={...s,messages:m};if(this.contextWindowStateManager&&this.contextWindowStateManager.recordPruneOperation(this.getConversationId(),p.tokensReclaimed),await this.countRequestTokens(u,t,u.model)<=o||m.length===s.messages.length)return u;s=u}return e}async pruneToMaxMessageHistory(e){let t=this.contextWindowConfig?.maxMessageHistoryLength;if(!t||e.messages.length<=t)return e;let o=this.contextWindowConfig?.retainSystemMessages??!0,n=[];e.messages.forEach((l,p)=>{o&&l.role==="system"||l.role!=="tool"&&n.push(p)});let s=Math.max(0,e.messages.length-t);if(s===0)return e;let i=new Set(n.slice(0,s)),a=e.messages.filter((l,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,n=o.filter(C=>C.role==="system"),s=o.filter(C=>C.role!=="system");if(s.length<4)return e;let i=s.slice(-4),a=s.slice(0,-4);if(a.length<2)return e;let l=this.contextWindowConfig?.summarizerModel||e.model,p=Fs(a,{model:l,maxSummaryTokens:500}),d=await Fe(t.generate({model:l,messages:p,max_tokens:500,temperature:0,response_format:"text",signal:e.signal}),e.signal);if(!d.content)throw new kn("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let m=await this.countRequestTokens({...e,messages:a},t,l),u=qs(d.content,a,m),b=js(u);if(!b.valid)throw new kn(`Summarization result is invalid: ${b.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",d.content);let h=Nr(u.summary,a.length),T=[...n,h,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),u.tokensSaved),{...e,messages:T}}async enforceContextWindow(e,t){if(!this.contextWindowConfig||this.contextWindowConfig.enabled===!1)return e;let o=await this.pruneToMaxMessageHistory(e),n=await this.getModelInfo(t,o.model),s=n?.contextWindow??1e5,i=o.max_tokens??n?.maxOutputTokens??1024,a=this.contextWindowConfig.outputTokenBuffer??1.15,l=Ns(i,a),p=Math.max(0,s-l),d=Math.floor(s*((this.contextWindowConfig.pruneThreshold??85)/100)),m=Math.min(p,d),u=await this.countRequestTokens(o,t,o.model);if(this.contextWindowStateManager&&(this.contextWindowStateManager.updateTokenCount(this.getConversationId(),u),u>m&&this.contextWindowStateManager.recordWarning(this.getConversationId())),u<=m)return o;let b=this.contextWindowConfig.strategy??"prune";if(b==="fail"&&u>p)throw new Cn("Context window exceeded by request messages",this.getConversationId(),u,p,b);if(b==="summarize")try{let T=await this.summarizeConversation(o,t);if(await this.countRequestTokens(T,t,T.model)<=p)return T;o=await this.pruneConversation(T,t,p)}catch(T){if(T instanceof A)throw T;o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let h=await this.countRequestTokens(o,t,o.model);if(h>p&&b==="fail")throw new Cn("Context window exceeded after attempted cleanup",this.getConversationId(),h,p,b);return o}isBypassed(e){let t=this.hitlConfig;if(!t||t.enabled===!1)return!0;let o=t.confirmationMode??"all";if(o==="off"||o==="high-only"&&e.confirmation?.level==="medium")return!0;let n=t.bypass??{};return!!(n.tools?.includes(e.name)||n.categories?.includes(e.category)||e.confirmation&&n.levels?.includes(e.confirmation.level))}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new M("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new M(`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 M(`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,k(`[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()),k(`[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,l=this.injectBaseAgentContext(e,i);l=this.injectOverrideSystemPrompt(l),l=this.injectModeSystemPrompt(l,i),l=await this.injectModeRules(l,i);let p=t||this.defaultProvider,d=await this.enrichRequestWithTools(l,i),m=d.request,u=d.requestToolMap;m=await this.enforceContextWindow(m,n);let b=a.toolChoicePolicy||process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||"auto",h=(m.tools?.length||0)>0,T=m.tool_choice!=null,C=Ql(m.messages),S=Xl(m.messages);!T&&h&&(b==="required"||b==="required_for_actions"&&C)&&(m.tool_choice="required");let v=n?.constructor?.name||"UnknownProvider",_=i?.response_format,E={...this.stripRequestTools(m),__toolpack_request_id:s,..._?{response_format:_}:{}};k(`[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=${b} needsTools=${C} autoExecute=${a.enabled&&a.autoExecute}`),Bs(s,m.tools),Fr(s,m.messages);let j=re=>Fe(Il(()=>n.generate(re),{signal:e.signal,onRetry:(H,ee)=>k(`[AIClient][${s}] Rate limited \u2014 retrying in ${ee/1e3}s (attempt ${H}/3)`)}),e.signal),R=await j(E);if(y(`[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||u.size>0||(i?.customTools?.length??0)>0)){let re=ut(m.messages),H=this.queryClassifier.classify(re),ee=a.maxToolRounds,xe=m.maxToolRounds!==void 0?m.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(H,ee);m.maxToolRounds!==void 0?y(`[AIClient][${s}] maxToolRounds overridden per-request: ${xe} (classifier bypassed)`):xe!==ee?k(`[AIClient][${s}] Query classified as ${H.type} (confidence: ${H.confidence.toFixed(2)}), adjusted maxToolRounds: ${ee} \u2192 ${xe}`):y(`[AIClient][${s}] Query classified as ${H.type} (confidence: ${H.confidence.toFixed(2)}), keeping maxToolRounds: ${xe}`);let pe=0,Q=[...m.messages];for(R.tool_calls&&R.tool_calls.length>0&&k(`[AIClient] Received ${R.tool_calls.length} tool call(s): ${R.tool_calls.map(G=>G.name).join(", ")}`);R.tool_calls&&R.tool_calls.length>0&&pe<xe;){if(e.signal?.aborted)throw k(`[AIClient][${s}] generate() aborted by signal`),new A;pe++,k(`[AIClient][${s}] generate() tool round ${pe}/${xe} tool_calls=${R.tool_calls.length}`),Q.push({role:"assistant",content:R.content||"",tool_calls:R.tool_calls.map(B=>({id:B.id,type:"function",function:{name:B.name,arguments:JSON.stringify(B.arguments)}}))});let G=this.toolOrchestrator.shouldUseParallelExecution(R.tool_calls),K=3,Ae=R.tool_calls,ze=R.tool_calls.filter(B=>B.name==="web.fetch");if(ze.length>K){k(`[AIClient][${s}] Limiting web.fetch calls from ${ze.length} \u2192 ${K} to prevent context overflow`);let B=ze.slice(0,K);Ae=[...R.tool_calls.filter(be=>be.name!=="web.fetch"),...B];let J=ze.slice(K);for(let be of J)Q.push({role:"tool",tool_call_id:be.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let me=5e4,ye=0;if(G){k(`[AIClient][${s}] Using parallel execution for ${Ae.length} tools`);let B;try{B=await Fe(this.toolOrchestrator.executeWithDependencies(Ae,D=>this.executeTool(D,u,i,pe,e.signal),5),e.signal)}catch(D){if(D instanceof A)throw D;ge(`[AIClient][${s}] Parallel tool execution failed: ${D.message}`),B=new Map(Ae.map(J=>[J.id,JSON.stringify({error:D.message??"Tool execution failed"})]))}for(let D of Ae){let J=B.get(D.id)??JSON.stringify({error:"Tool execution result missing"}),be=typeof J=="string"?J:JSON.stringify(J),Et=me-ye,se=be.startsWith("data:image/"),ie;se?ie=be:ye+be.length>me?(I(`[AIClient][${s}] Tool output budget exceeded (${me} chars)`),ie=this.budgetTruncate(be,Et)):typeof J=="string"&&J.length>this.toolResultMaxChars?ie=`${J.slice(0,this.toolResultMaxChars)}
414
+ [TRUNCATED tool result: ${J.length} chars]`:ie=be;let $=typeof ie=="string"?ie:JSON.stringify(ie);se||(ye+=$.length),Q.push({role:"tool",tool_call_id:D.id,content:ie})}y(`[AIClient][${s}] Round tool output size: ${ye} chars (budget: ${me})`)}else{k(`[AIClient][${s}] Using sequential execution for ${Ae.length} tools`);for(let B of Ae){let D;try{D=await this.executeTool(B,u,i,pe,e.signal)}catch($){if($ instanceof A)throw $;D=JSON.stringify({error:$.message??"Tool execution failed"})}let J=typeof D=="string"?D:JSON.stringify(D),be=me-ye,Et=J.startsWith("data:image/"),se;Et?se=J:ye+J.length>me?(I(`[AIClient][${s}] Tool output budget exceeded (${me} chars)`),se=this.budgetTruncate(J,be)):typeof D=="string"&&D.length>this.toolResultMaxChars?se=`${D.slice(0,this.toolResultMaxChars)}
415
+ [TRUNCATED tool result: ${D.length} chars]`:se=J;let ie=typeof se=="string"?se:JSON.stringify(se);Et||(ye+=ie.length),Q.push({role:"tool",tool_call_id:B.id,content:se})}y(`[AIClient][${s}] Round tool output size: ${ye} chars (budget: ${me})`)}if(e.signal?.aborted)throw k(`[AIClient][${s}] generate() aborted by signal during tool execution`),new A;let je={...m,messages:Q,__toolpack_request_id:s,..._?{response_format:_}:{}},He=o?.getLatestRequestTools?.()??[];if(He.length>0){let B=new Map((m.requestTools??[]).map(D=>[D.name,D]));for(let D of He)B.set(D.name,D);je.requestTools=Array.from(B.values());for(let D of He)u.set(D.name,D)}let _e=this.stripRequestTools((await this.enrichRequestWithTools(je,i)).request);_e=await this.enforceContextWindow(_e,n),_e.tool_choice==="required"&&(_e.tool_choice=S?"none":"auto",k(`[AIClient][${s}] generate() followup tool_choice override required->${_e.tool_choice}`)),gt("debug")&&(y(`[AIClient][${s}] generate() followup request messages=${Q.length}`),Fr(s,Q)),R=await j(_e),y(`[AIClient][${s}] generate() followup response finish_reason=${R.finish_reason??"unknown"} tool_calls=${R.tool_calls?.length||0} content=${R.content||""}`)}if(pe>=xe&&!e.signal?.aborted&&R.tool_calls&&R.tool_calls.length>0){k(`[AIClient][${s}] Tool-round cap (${xe}) hit with pending tool calls; requesting graceful conclusion`),Q.push({role:"assistant",content:R.content||"",tool_calls:R.tool_calls.map(K=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments)}}))});for(let K of R.tool_calls)Q.push({role:"tool",tool_call_id:K.id,content:"[Tool call skipped: maximum tool rounds reached]"});Q.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 G={...m,messages:Q,__toolpack_request_id:s,tools:[],requestTools:[],tool_choice:void 0};try{R=await j(await this.enforceContextWindow(G,n)),k(`[AIClient][${s}] Graceful conclusion received content_length=${R.content?.length??0}`)}catch(K){if(K instanceof A)throw K;I(`[AIClient][${s}] Graceful conclusion call failed: ${K?.message??K}; 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),l=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,u=d.requestToolMap;m=await this.enforceContextWindow(m,n);let b=l.toolChoicePolicy||process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||"auto",h=(m.tools?.length||0)>0,T=m.tool_choice!=null,C=Ql(m.messages),S=Xl(m.messages);!T&&h&&(b==="required"||b==="required_for_actions"&&C)&&(m.tool_choice="required");let v=n?.constructor?.name||"UnknownProvider",_=a?.response_format,E={...this.stripRequestTools(m),__toolpack_request_id:s,..._?{response_format:_}:{}};if(k(`[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=${b} needsTools=${C} autoExecute=${l.enabled&&l.autoExecute}`),Bs(s,m.tools),Fr(s,m.messages),!l.autoExecute||!this.toolRegistry&&u.size===0&&(a?.customTools?.length??0)===0){if(yield*vn(n.stream(E),e.signal),e.signal?.aborted)throw new A;return}let j=[...m.messages],R=0,re=!1,H=ut(m.messages),ee=this.queryClassifier.classify(H),xe=l.maxToolRounds,pe=m.maxToolRounds!==void 0?m.maxToolRounds:this.queryClassifier.getToolRoundsAdjustment(ee,xe);for(m.maxToolRounds!==void 0?y(`[AIClient][${s}] stream() maxToolRounds overridden per-request: ${pe} (classifier bypassed)`):pe!==xe&&k(`[AIClient][${s}] stream() Query classified as ${ee.type} (confidence: ${ee.confidence.toFixed(2)}), adjusted maxToolRounds: ${xe} \u2192 ${pe}`);R<=pe;){if(e.signal?.aborted)throw k(`[AIClient][${s}] stream() aborted by signal`),new A;let Q="",G=[];R++,k(`[AIClient][${s}] stream() round_start ${R}/${pe}`);let K=null,Ae={...m,messages:j,..._?{response_format:_}:{}},ze=o?.getLatestRequestTools?.()??[];if(ze.length>0){let $=new Map((m.requestTools??[]).map(q=>[q.name,q]));for(let q of ze)$.set(q.name,q);Ae.requestTools=Array.from($.values());for(let q of ze)u.set(q.name,q)}let me=this.stripRequestTools((await this.enrichRequestWithTools(Ae,a)).request);me=await this.enforceContextWindow(me,n),R>1&&me.tool_choice==="required"&&(me.tool_choice=S?"none":"auto",k(`[AIClient][${s}] stream() round_${R} tool_choice override required->${me.tool_choice}`));for await(let $ of vn(n.stream(me),e.signal)){if(e.signal?.aborted)throw k(`[AIClient][${s}] stream() aborted by signal during chunk processing`),new A;$.tool_calls&&$.tool_calls.length>0&&(G.push(...$.tool_calls),y(`[AIClient][${s}] stream() tool_calls_chunk count=${$.tool_calls.length} names=${$.tool_calls.map(q=>q.name).join(", ")}`),yield $),$.delta&&(Q+=$.delta,yield $),$.finish_reason&&(K=$.finish_reason),$.finish_reason==="stop"&&(yield $)}if(e.signal?.aborted)throw k(`[AIClient][${s}] stream() aborted by signal while waiting for the provider`),new A;if(y(`[AIClient][${s}] stream() round_end finish_reason=${K??"unknown"} accumulated_len=${Q.length} tool_calls_total=${G.length} content=${Q}`),G.length===0)break;k(`[AIClient][${s}] stream() received ${G.length} tool call(s): ${G.map($=>$.name).join(", ")}`),k(`[AIClient][${s}] stream() tool round ${R}/${pe}`),j.push({role:"assistant",content:Q||"",tool_calls:G.map($=>({id:$.id,type:"function",function:{name:$.name,arguments:JSON.stringify($.arguments)}}))});let ye=3,je=G,He=G.filter($=>$.name==="web.fetch");if(He.length>ye){k(`[AIClient][${s}] Limiting web.fetch calls from ${He.length} \u2192 ${ye} to prevent context overflow`);let $=He.slice(0,ye);je=[...G.filter(xn=>xn.name!=="web.fetch"),...$];let Pe=He.slice(ye);for(let xn of Pe)j.push({role:"tool",tool_call_id:xn.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let _e=5e4,B=0,D=[],J=!1,be=setInterval(()=>{J||D.push({delta:""})},500),Et=Date.now(),se,ie;try{if(je.length>=2)k(`[AIClient][${s}] stream() using parallel execution for ${je.length} tools`),ie=new Map,se=await Fe(this.toolOrchestrator.executeWithDependencies(je,async $=>{let q=Date.now(),Pe=await this.executeTool($,u,a,R,e.signal);return ie.set($.id,Date.now()-q),Pe},5),e.signal);else{k(`[AIClient][${s}] stream() executing single tool sequentially`),ie=new Map,se=new Map;for(let $ of je){let q=Date.now(),Pe=await this.executeTool($,u,a,R,e.signal);ie.set($.id,Date.now()-q),se.set($.id,Pe)}}}finally{J=!0,clearInterval(be)}if(e.signal?.aborted)throw k(`[AIClient][${s}] stream() aborted by signal during tool execution`),new A;for(;D.length>0;)yield D.shift();await new Promise($=>setTimeout($,0)),y(`[AIClient][${s}] stream() tool batch completed in ${Date.now()-Et}ms`);for(let $ of je){let q=se.get($.id),Pe=typeof q=="string"?q:JSON.stringify(q),xn=_e-B,sx=ie.get($.id)??0,Ml=Pe.startsWith("data:image/"),Ke;Ml?Ke=Pe:B+Pe.length>_e?(I(`[AIClient][${s}] Tool output budget exceeded (${_e} chars)`),Ke=this.budgetTruncate(Pe,xn)):typeof q=="string"&&q.length>this.toolResultMaxChars?Ke=`${q.slice(0,this.toolResultMaxChars)}
416
+ [TRUNCATED tool result: ${q.length} chars]`:Ke=Pe;let Nl=typeof Ke=="string"?Ke:JSON.stringify(Ke);Ml||(B+=Nl.length),j.push({role:"tool",tool_call_id:$.id,content:Ke}),yield{delta:"",tool_calls:[{...$,result:Nl,duration:sx}]}}y(`[AIClient][${s}] Round tool output size: ${B} chars (budget: ${_e})`),gt("debug")&&(y(`[AIClient][${s}] stream() after_tools messages=${j.length}`),Fr(s,j)),R>pe&&(re=!0)}if(re&&!e.signal?.aborted){k(`[AIClient][${s}] Tool-round cap (${pe}) 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 Q={...m,messages:j,tools:[],requestTools:[],tool_choice:void 0};try{let G=await this.enforceContextWindow(Q,n);for await(let K of vn(n.stream(G),e.signal))yield K;if(e.signal?.aborted)throw new A;k(`[AIClient][${s}] Graceful conclusion stream complete`)}catch(G){if(G instanceof A)throw G;I(`[AIClient][${s}] Graceful conclusion stream failed: ${G?.message??G}`)}}}catch(s){if(s instanceof A){yield{delta:"",finish_reason:"aborted"};return}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 k(`[AIClient] Mode "${t.displayName}" blocks all tools`),{request:e,requestToolMap:new Map};let o=this.buildRequestToolMap(e.requestTools),n=Array.from(o.values()).map(h=>this.requestToolToSchema(h)),s=o.size>0,i=t?.toolsConfig?{...this.toolsConfig,...t.toolsConfig}:this.toolsConfig,a=this.toolDefinitionsToSchemas(t?.customTools??[]),l=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 w=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(l)),v=w===e.tools?e:{...e,tools:w};return{request:this.injectRequestToolGuidance(v,w),requestToolMap:o}}let h=await this.toolRouter.resolve(e.messages,this.toolRegistry,p);if(y(`[AIClient] Resolved ${h.length} tools to send: ${h.map(w=>w.name).join(", ")||"none"}`),t&&h.length>0){let w=h.length;h=this.filterSchemasByMode(h,t);let v=w-h.length;v>0&&k(`[AIClient] Mode "${t.displayName}" filtered out ${v} tools`)}let T=new Set(e.tools.map(w=>w.function.name)),C=h.filter(w=>!T.has(w.name)).map(w=>({type:"function",function:{name:w.name,description:w.description,parameters:w.parameters}}));if(C.length===0){y(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`);let w=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(l)),v=w===e.tools?e:{...e,tools:w};return{request:this.injectRequestToolGuidance(v,w),requestToolMap:o}}let S={...e,tools:this.mergeToolCallRequests([...e.tools,...C],this.schemasToToolCallRequests(l))};return p.toolSearch?.enabled&&this.toolRegistry&&(S=this.injectToolSearchPrompt(S)),{request:this.injectRequestToolGuidance(S,S.tools),requestToolMap:o}}if(!this.toolRegistry){y("[AIClient] Tool registry not configured, skipping tool resolution");let h=this.schemasToToolCallRequests(l),T=h.length>0?{...e,tools:h}:e;return{request:this.injectRequestToolGuidance(T,h),requestToolMap:o}}let d=this.toolRegistry,m=await this.toolRouter.resolve(e.messages,d,p);if(y(`[AIClient] Resolved ${m.length} tools to send: ${m.map(h=>h.name).join(", ")||"none"}`),t&&m.length>0){let h=m.length;m=this.filterSchemasByMode(m,t);let T=h-m.length;T>0&&k(`[AIClient] Mode "${t.displayName}" filtered out ${T} tools`)}let u=this.schemasToToolCallRequests(this.mergeSchemas(m,l));if(u.length===0)return{request:e,requestToolMap:o};let b={...e,tools:u};return i.toolSearch?.enabled&&d&&(b=this.injectToolSearchPrompt(b)),{request:this.injectRequestToolGuidance(b,u),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((d,m)=>{if(m!==c)return d;let f=typeof d.content=="string"?d.content:"";return f.includes(n)?d:{...d,content:`${f}
421
+ `)}`,l=e.messages.findIndex(p=>p.role==="system");if(l>=0){let p=e.messages.map((d,m)=>{if(m!==l)return d;let u=typeof d.content=="string"?d.content:"";return u.includes(n)?d:{...d,content:`${u}
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"?(N(`[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(pt(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"?(I(`[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(dt(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}
424
424
 
425
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}
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||Ul({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}
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||zl({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
- ${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(`
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 l=this.toolRegistry?.get(a);return l?` - **${l.name}**: ${l.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
- ${Mr(this.toolRegistry)}
442
+ ${Ir(this.toolRegistry)}
443
443
 
444
444
  When you need a tool:
445
445
  1. Check if it's in your current tool list
@@ -447,13 +447,13 @@ When you need a tool:
447
447
  3. After discovering tools, you can call them directly in subsequent turns
448
448
 
449
449
  NEVER guess or hallucinate tool names. ALWAYS use tool.search to discover tools you don't have.
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}
450
+ `.trim();if(t){let i=e.messages.map(a=>{if(a.role==="system"){let l=typeof a.content=="string"?a.content:"";return{...a,content:`${l}
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}),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(pt(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){N(`[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 w=`[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:w,duration:v}),this.emit("tool:log",{id:e.id,name:e.name,arguments:d,result:w,duration:v,status:"success",timestamp:Date.now()}),w}C.action==="modify"&&(d=C.args)}let f=o?.toolsConfig?.additionalConfigurations?{...this.toolsConfig?.additionalConfigurations,...o.toolsConfig.additionalConfigurations}:this.toolsConfig?.additionalConfigurations??{},b={workspaceRoot:process.cwd(),actor:(typeof this.actor=="function"?this.actor():this.actor)??void 0,config:f,log:C=>S(`[Tool] ${C}`),processRegistry:this.toolRegistry?.runtimeContext?.processRegistry,githubTokenStore:this.toolRegistry?.runtimeContext?.githubTokenStore},h=await p.execute(d,b),T=Date.now()-s;this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof h=="string"?h.startsWith("data:image/")?h:h.substring(0,200):JSON.stringify(h).substring(0,200),duration:T}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:h,duration:T,status:"success",timestamp:Date.now()});let k=typeof h=="string"?h.length:JSON.stringify(h).length;return S(`[AIClient] Tool ${e.name} executed successfully in ${T}ms result_len=${k}`),ut("debug")&&y(`[AIClient] Tool ${e.name} result_preview=${A(h,400)}`),typeof h=="string"?h:JSON.stringify(h)}catch(d){let m=Date.now()-s,f=d.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:f,duration:m}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:f}),duration:m,status:"error",timestamp:Date.now()}),fe(`[AIClient] Tool ${e.name} failed: ${A(f,300)}`),JSON.stringify({error:f})}}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([Je()],a).length>0))return N("[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(T=>T.tool),a),f=new Set(m.map(T=>T.name)),b=p.length;p=p.filter(T=>f.has(T.toolName));let h=b-p.length;h>0&&y(`[AIClient] tool.search filtered out ${h} 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),y(`[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 O?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();var Ks=x(require("@anthropic-ai/sdk"),1),ec=require("@anthropic-ai/sdk/helpers/zod");l();pe();var Q=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}};pe();_();Ae();var Sn=class extends Q{client;constructor(e,t){super(),this.client=new Ks.default({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(b=>({name:this.sanitizeToolName(b.function.name),description:b.function.description,input_schema:b.function.parameters})),e.tool_choice==="required"?i.tool_choice={type:"any"}:e.tool_choice==="none"?delete i.tools:i.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&y(`[Anthropic][${t}] First tool: ${A(i.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] generate() request: model=${i.model}, messages=${i.messages.length}, tools=${i.tools?.length||0}, tool_choice=${i.tool_choice?.type??"unset"}`),oe(t,"Anthropic",i.messages);let a=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format;a&&(i.output_config={format:(0,ec.zodOutputFormat)(e.response_format)});let p=a?await this.client.messages.parse(i,e.signal?{signal:e.signal}:void 0):await this.client.messages.create(i,e.signal?{signal:e.signal}:void 0),d=[],m=[];for(let b of p.content)b.type==="text"?d.push(b.text):b.type==="tool_use"&&m.push({id:b.id,name:this.restoreToolName(b.name,e.tools),arguments:b.input});y(`[Anthropic][${t}] Response finish_reason=${p.stop_reason} tool_calls=${m.length} content_preview=${A(d.join(""),200)}`);let f={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&&(f.data=p.parsed_output),f}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),n={model:e.model,messages:o.userMessages,system:o.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(n.tools=e.tools.map(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"},y(`[Anthropic][${t}] Sending ${n.tools?.length||0} tools with tool_choice: ${n.tool_choice?.type||"unset"}`),n.tools&&n.tools.length>0&&y(`[Anthropic][${t}] First tool: ${A(n.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice?.type??"unset"}`),oe(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&&(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),d.type==="message_stop"&&(Qe(`[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(()=>(Ae(),Mt));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:Ye(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[,f,b]=m;return f.startsWith("image/")?{type:"image",source:{type:"base64",media_type:f,data:b}}:{type:"document",source:{type:"base64",media_type:f,data:b}}}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 Ks.default.APIError){let t=e.message;return e.status===401?new ue(t,e):e.status===429?new ie(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new L(t,"ANTHROPIC_ERROR",e.status||500,e)}return new L("Unknown Anthropic error","UNKNOWN",500,e)}};l();var tc=x(require("@anthropic-ai/vertex-sdk"),1);pe();_();var _n=class extends Q{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 tc.default({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}`),oe(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=${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"}),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="",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 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(()=>(Ae(),Mt)),{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 ue(t,e):e?.status===429?new ie(t,void 0,e):e?.status>=400&&e?.status<500?new M(t,e):new L(t||"Anthropic Vertex error","ANTHROPIC_VERTEX_ERROR",e?.status??500,e)}};l();var oc=require("@google/genai"),nc=require("zod-to-json-schema");pe();_();Ae();var Pn=class r extends Q{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 ue("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 oc.GoogleGenAI({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}`),oe(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 f of a){let b=f.parts;if(Array.isArray(b))for(let h=0;h<b.length;h++){let T=b[h];T?.inlineData!==void 0&&!T.inlineData?.data&&b.splice(h--,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 f=d.map(b=>b.id).join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(f,m)}return y(`[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()}`;y(`[VertexAI][${t}] stream() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),oe(t,"VertexAI",e.messages);let{model:o,config:n}=this.buildRequestParams(e),{history:s,lastUserMessage:i}=this.formatHistory(e.messages),a=i!==null?[...s,{role:"user",parts:typeof i=="string"?[{text:i}]:i}]:s;for(let m of a){let f=m.parts;if(Array.isArray(f))for(let b=0;b<f.length;b++){let h=f[b];h?.inlineData!==void 0&&!h.inlineData?.data&&f.splice(b--,1)}}let c=await this.ai.models.generateContentStream({model:o,contents:a,config:n}),p=[],d=[];for await(let m of c)for(let f of m.candidates??[])for(let b of f.content?.parts??[])if(d.push(b),b.functionCall){let h=b.functionCall;y(`[VertexAI][${t}] stream tool_call name=${h.name}`);let T=`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;p.push(T),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:T,name:this.restoreToolName(h.name,e.tools),arguments:h.args??{}}]}}else b.text&&(yield{delta:b.text});if(p.length>0&&d.length>0){let m=p.join("|"),f={role:"model",parts:d};this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(m,f)}}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((0,nc.zodToJsonSchema)(e.response_format))}:{}};return e.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(n=>({name:this.sanitizeToolName(n.function.name),description:n.function.description,parameters:this.sanitizeSchema(n.function.parameters)}))}]),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),f=m?null:Ye(d),b=[{functionResponse:{name:p,response:{name:p,content:m||f?"File data attached as sibling part.":d}}}];return m&&b.push({inlineData:{mimeType:m[1],data:m[2]}}),f&&b.push({fileData:{mimeType:f.mimeType,fileUri:f.url}}),{role:"function",parts:b}}if(c.role==="assistant"&&c.tool_calls&&c.tool_calls.length>0){let p=c.tool_calls.map(f=>f.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 f of c.tool_calls)m.push({functionCall:{name:this.sanitizeToolName(f.function.name),args:typeof f.function.arguments=="string"?JSON.parse(f.function.arguments||"{}"):f.function.arguments}});return{role:"model",parts: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 ie(t,void 0,e):e?.status===401||e?.status===403||t.includes("UNAUTHENTICATED")||t.includes("PERMISSION_DENIED")?new ue(t,e):e?.status>=400&&e?.status<500?new M(t,e):new L(t||"Vertex AI Error","VERTEXAI_ERROR",e?.status??500,e)}};l();var rc=require("@google/generative-ai"),Js=require("zod-to-json-schema");pe();_();var Rn=class r extends Q{genAI;rawContentCache=new Map;static RAW_CONTENT_CACHE_MAX=500;constructor(e){super(),this.genAI=new rc.GoogleGenerativeAI(e)}supportsFileUpload(){return!0}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[o,n]of Object.entries(e))o==="additionalProperties"||o==="exclusiveMinimum"||o==="exclusiveMaximum"||o==="$schema"||o==="$id"||o==="definitions"||o==="$defs"||(typeof n=="object"&&n!==null?Array.isArray(n)?t[o]=n.map(s=>this.sanitizeSchema(s)):t[o]=this.sanitizeSchema(n):t[o]=n);return t}async uploadFile(e){try{let t=await import("fs"),o=await import("path");if(!e.filePath)throw new 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),d=JSON.stringify({file:{displayName:s}}),m=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,s){if(s?.aborted)throw new A;let i=Date.now();this.emit("tool:started",{toolName:e.name,toolCallId:e.id,status:"started",args:e.arguments}),k(`[AIClient] Executing tool: ${e.name} with args: ${N(e.arguments,500)}`);let a=t.get(e.name),l=a?void 0:o?.customTools?.find(m=>m.name===e.name),p=a||l?void 0:this.toolRegistry?.get(e.name);if(!a&&!l&&!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()-i}),JSON.stringify({error:m})}if(dt(e.name)){let m=this.executeToolSearch(e.arguments,o),u=Date.now()-i;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:u}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:m,duration:u,status:"success",timestamp:Date.now()}),m}let d=a||l||p;if(!d){I(`[AIClient] Tool '${e.name}' not found in registry or mode`);let m=this.findSimilarToolName(e.name),u=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:u,duration:Date.now()-i}),JSON.stringify({error:u})}try{let m=e.arguments,u=l??p;if(u?.confirmation&&this.onToolConfirm&&!this.isBypassed(u)){this.emit("tool:confirmation_requested",{tool:u,args:m,level:u.confirmation.level,reason:u.confirmation.reason});let w=await Fe(this.onToolConfirm(u,m,{roundNumber:n,conversationId:this.conversationId}),s);if(this.emit("tool:confirmation_resolved",{tool:u,args:m,level:u.confirmation.level,reason:u.confirmation.reason,decision:w}),w.action==="deny"){let v=`[Execution denied by user${w.reason?": "+w.reason:""}]`,_=Date.now()-i;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:v,duration:_}),this.emit("tool:log",{id:e.id,name:e.name,arguments:m,result:v,duration:_,status:"success",timestamp:Date.now()}),v}w.action==="modify"&&(m=w.args)}let b=o?.toolsConfig?.additionalConfigurations?{...this.toolsConfig?.additionalConfigurations,...o.toolsConfig.additionalConfigurations}:this.toolsConfig?.additionalConfigurations??{},h={workspaceRoot:process.cwd(),actor:(typeof this.actor=="function"?this.actor():this.actor)??void 0,config:b,log:w=>k(`[Tool] ${w}`),processRegistry:this.toolRegistry?.runtimeContext?.processRegistry,githubTokenStore:this.toolRegistry?.runtimeContext?.githubTokenStore,signal:s},T=await Fe(Promise.resolve(d.execute(m,h)),s),C=Date.now()-i;this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof T=="string"?T.startsWith("data:image/")?T:T.substring(0,200):JSON.stringify(T).substring(0,200),duration:C}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:T,duration:C,status:"success",timestamp:Date.now()});let S=typeof T=="string"?T.length:JSON.stringify(T).length;return k(`[AIClient] Tool ${e.name} executed successfully in ${C}ms result_len=${S}`),gt("debug")&&y(`[AIClient] Tool ${e.name} result_preview=${N(T,400)}`),typeof T=="string"?T:JSON.stringify(T)}catch(m){let u=Date.now()-i,b=m.message||"Tool execution failed";if(this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:b,duration:u}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:b}),duration:u,status:"error",timestamp:Date.now()}),ge(`[AIClient] Tool ${e.name} failed: ${N(b,300)}`),m instanceof A)throw m;return JSON.stringify({error:b})}}findSimilarToolName(e){if(!this.toolRegistry)return null;let t=this.toolRegistry.getAll(),o=e.replace(/_/g,".");if(t.some(l=>l.name===o))return o;let n=e.replace(/\./g,"_");if(t.some(l=>l.name===n))return n;let s=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(l=>l.name===s))return s;let i=null,a=1/0;for(let l of t){let p=this.levenshteinDistance(e.toLowerCase(),l.name.toLowerCase());p<=2&&p<a&&(a=p,i=l.name)}return i}levenshteinDistance(e,t){let o=[];for(let n=0;n<=t.length;n++)o[n]=[n];for(let n=0;n<=e.length;n++)o[0][n]=n;for(let n=1;n<=t.length;n++)for(let s=1;s<=e.length;s++)t.charAt(n-1)===e.charAt(s-1)?o[n][s]=o[n-1][s-1]:o[n][s]=Math.min(o[n-1][s-1]+1,o[n][s-1]+1,o[n-1][s]+1);return o[t.length][e.length]}executeToolSearch(e,t){let{query:o,category:n}=e,s=this.toolsConfig.toolSearch?.searchResultLimit??5,i=typeof n=="string"&&n.length>0?n:void 0,a=t===void 0?this.activeMode:t;if(a&&!(this.filterSchemasByMode([Qe()],a).length>0))return I("[AIClient] tool.search blocked by active mode"),JSON.stringify({query:o,found:0,tools:[],hint:"tool.search is not allowed in the current mode."});k(`[AIClient] Executing tool.search: query="${o}" category=${i||"all"} limit=${s}`);let l=a?Math.max(s*4,s):s,p=this.bm25Engine.search(o,{limit:l,category:i});if(i&&p.length===0&&(k(`[AIClient] tool.search category="${i}" returned 0 results; retrying without category filter`),p=this.bm25Engine.search(o,{limit:l})),a&&p.length>0){let m=this.filterSchemasByMode(p.map(T=>T.tool),a),u=new Set(m.map(T=>T.name)),b=p.length;p=p.filter(T=>u.has(T.toolName));let h=b-p.length;h>0&&y(`[AIClient] tool.search filtered out ${h} 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),y(`[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 A||e instanceof M?e:new F(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.]"}};c();c();var Qs=x(require("@anthropic-ai/sdk"),1),nc=require("@anthropic-ai/sdk/helpers/zod");c();le();var X=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new O(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new O(`File deletion API is not supported by ${this.getDisplayName()}`)}async countTokens(e,t){return null}};le();P();Me();var Rn=class extends X{client;constructor(e,t){super(),this.client=new Qs.default({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new O("Anthropic uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"Anthropic"}async getModels(){return[{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:64e3},{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-6",displayName:"Claude Opus 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),n=o.system,s=o.userMessages,i={model:e.model,messages:s,system:n,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!1};e.tools&&e.tools.length>0?(i.tools=e.tools.map(b=>({name:this.sanitizeToolName(b.function.name),description:b.function.description,input_schema:b.function.parameters})),e.tool_choice==="required"?i.tool_choice={type:"any"}:e.tool_choice==="none"?delete i.tools:i.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${i.tools?.length||0} tools with tool_choice: ${i.tool_choice?.type||"unset"}`),i.tools&&i.tools.length>0&&y(`[Anthropic][${t}] First tool: ${N(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"}`),ne(t,"Anthropic",i.messages);let a=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format;a&&(i.output_config={format:(0,nc.zodOutputFormat)(e.response_format)});let p=a?await this.client.messages.parse(i,e.signal?{signal:e.signal}:void 0):await this.client.messages.create(i,e.signal?{signal:e.signal}:void 0),d=[],m=[];for(let b of p.content)b.type==="text"?d.push(b.text):b.type==="tool_use"&&m.push({id:b.id,name:this.restoreToolName(b.name,e.tools),arguments:b.input});y(`[Anthropic][${t}] Response finish_reason=${p.stop_reason} tool_calls=${m.length} content_preview=${N(d.join(""),200)}`);let u={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&&(u.data=p.parsed_output),u}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"},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: ${N(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"}`),ne(t,"Anthropic",n.messages);let s=await this.client.messages.create(n,e.signal?{signal:e.signal}:void 0),i="",a="",l="",p=!1;for await(let 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,l=""),d.type==="content_block_delta"&&(d.delta.type==="text_delta"?yield{delta:d.delta.text}:d.delta.type==="input_json_delta"&&p&&(l+=d.delta.partial_json)),d.type==="content_block_stop"&&p&&(y(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${a}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:i,name:this.restoreToolName(a,e.tools),arguments:JSON.parse(l||"{}")}]},p=!1),d.type==="message_stop"&&(Ye(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new O("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(Me(),Ot));for(let i of e)if(i.role==="system"){if(typeof i.content=="string")o=i.content;else if(i.content!==null){let a=i.content.filter(l=>typeof l=="object"&&l.type==="text").map(l=>l.text).join(`
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),l=a.match(/^data:([\w/+.-]+);base64,(.+)$/s),p=l?null:et(a),d=l?l[1].startsWith("image/")?[{type:"image",source:{type:"base64",media_type:l[1],data:l[2]}}]:[{type:"document",source:{type:"base64",media_type:l[1],data:l[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 l=i.content.filter(p=>typeof p=="object"&&p.type==="text").map(p=>p.text).join(`
455
+ `);l&&a.push({type:"text",text:l})}for(let l of i.tool_calls)a.push({type:"tool_use",id:l.id,name:this.sanitizeToolName(l.function.name),input:typeof l.function.arguments=="string"?JSON.parse(l.function.arguments||"{}"):l.function.arguments});n.push({role:"assistant",content:a})}else{let a=[];typeof i.content=="string"?a=i.content:i.content!==null&&(a=(await Promise.all(i.content.map(async l=>{if(l.type==="text")return{type:"text",text:l.text};if(l.type==="image_url"){let p=l.image_url.url;if(p.startsWith("data:")){let 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(l.type==="image_data"||l.type==="image_file"){let{data:p,mimeType:d}=await s(l);return{type:"image",source:{type:"base64",media_type:d,data:p}}}if(l.type==="file"){let{url:p,mimeType:d}=l.file,m=p.match(/^data:([\w/+.-]+);base64,(.+)$/s);if(m){let[,u,b]=m;return u.startsWith("image/")?{type:"image",source:{type:"base64",media_type:u,data:b}}:{type:"document",source:{type:"base64",media_type:u,data:b}}}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 Qs.default.APIError){let t=e.message;return e.status===401?new fe(t,e):e.status===429?new ae(t,void 0,e):e.status&&e.status>=400&&e.status<500?new O(t,e):new F(t,"ANTHROPIC_ERROR",e.status||500,e)}return new F("Unknown Anthropic error","UNKNOWN",500,e)}};c();var rc=x(require("@anthropic-ai/vertex-sdk"),1);le();P();var $n=class extends X{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 rc.default({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}`),ne(t,"AnthropicVertex",s.messages);let i=await this.client.messages.create(s,e.signal?{signal:e.signal}:void 0),a=[],l=[];for(let p of i.content)p.type==="text"&&a.push(p.text),p.type==="tool_use"&&l.push({id:p.id,name:this.restoreToolName(p.name,e.tools),arguments:p.input});return y(`[AnthropicVertex][${t}] Response finish_reason=${i.stop_reason} tool_calls=${l.length} content_preview=${N(a.join(""),200)}`),{content:a.length>0?a.join(""):null,usage:{prompt_tokens:i.usage.input_tokens,completion_tokens:i.usage.output_tokens,total_tokens:i.usage.input_tokens+i.usage.output_tokens},finish_reason:this.mapFinishReason(i.stop_reason),tool_calls:l.length>0?l:void 0,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`anv-str-${Date.now()}`,{system:o,userMessages:n}=await this.toAnthropicMessages(e.messages),s={model:e.model,messages:n,system:o,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0&&(s.tools=e.tools.map(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"}),y(`[AnthropicVertex][${t}] stream() model=${s.model} messages=${s.messages.length} tools=${s.tools?.length??0}`);let i=await this.client.messages.create(s,e.signal?{signal:e.signal}:void 0),a="",l="",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,l=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(l,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 O("Embeddings are not supported by the Anthropic API.")}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name??e.replace(/_/g,".")}async toAnthropicMessages(e){let t,o=[];for(let n of e)if(n.role==="system")t=typeof n.content=="string"?n.content:"";else if(n.role==="tool"&&n.tool_call_id){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 l=a.match(/^data:(image\/\w+);base64,(.+)$/);if(l)return{type:"image",source:{type:"base64",media_type:l[1],data:l[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(()=>(Me(),Ot)),{data:l,mimeType:p}=await a(i);return{type:"image",source:{type:"base64",media_type:p,data:l}}}if(i.type==="file"){let{url:a,mimeType:l}=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 l.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 ae(t,void 0,e):e?.status>=400&&e?.status<500?new O(t,e):new F(t||"Anthropic Vertex error","ANTHROPIC_VERTEX_ERROR",e?.status??500,e)}};c();var sc=require("@google/genai"),ic=require("zod-to-json-schema");le();P();Me();var En=class r extends X{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 sc.GoogleGenAI({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}`),ne(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 u of a){let b=u.parts;if(Array.isArray(b))for(let h=0;h<b.length;h++){let T=b[h];T?.inlineData!==void 0&&!T.inlineData?.data&&b.splice(h--,1)}}e.signal&&(n.abortSignal=e.signal);let l=await this.ai.models.generateContent({model:o,contents:a,config:n}),{content:p,toolCalls:d,rawContent:m}=this.parseResponse(l,e.tools);if(d.length>0&&m){let u=d.map(b=>b.id).join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(u,m)}return y(`[VertexAI][${t}] Response finish_reason=${d.length>0?"tool_calls":"stop"} tool_calls=${d.length} content_preview=${N(p,200)}`),{content:p||null,usage:{prompt_tokens:l.usageMetadata?.promptTokenCount??0,completion_tokens:l.usageMetadata?.candidatesTokenCount??0,total_tokens:l.usageMetadata?.totalTokenCount??0},finish_reason:d.length>0?"tool_calls":"stop",tool_calls:d.length>0?d:void 0,raw:l}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`vtx-str-${Date.now()}`;y(`[VertexAI][${t}] stream() model=${e.model} messages=${e.messages.length} tools=${e.tools?.length??0}`),ne(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 u=m.parts;if(Array.isArray(u))for(let b=0;b<u.length;b++){let h=u[b];h?.inlineData!==void 0&&!h.inlineData?.data&&u.splice(b--,1)}}e.signal&&(n.abortSignal=e.signal);let l=await this.ai.models.generateContentStream({model:o,contents:a,config:n}),p=[],d=[];for await(let m of l)for(let u of m.candidates??[])for(let b of u.content?.parts??[])if(d.push(b),b.functionCall){let h=b.functionCall;y(`[VertexAI][${t}] stream tool_call name=${h.name}`);let T=`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`;p.push(T),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:T,name:this.restoreToolName(h.name,e.tools),arguments:h.args??{}}]}}else b.text&&(yield{delta:b.text});if(p.length>0&&d.length>0){let m=p.join("|"),u={role:"model",parts:d};this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(m,u)}}catch(t){throw this.handleError(t)}}async embed(e){throw new O("Vertex AI embeddings are not supported by this adapter. Use the Gemini adapter (gemini provider) with text-embedding-004 instead.")}buildRequestParams(e){let t=e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format,o={systemInstruction:this.extractSystemInstruction(e.messages),maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||t)&&!e.tools?.length?"application/json":"text/plain",...t&&!e.tools?.length?{responseSchema:this.sanitizeSchema((0,ic.zodToJsonSchema)(e.response_format))}:{}};return e.tools&&e.tools.length>0&&(o.tools=[{functionDeclarations:e.tools.map(n=>({name:this.sanitizeToolName(n.function.name),description:n.function.description,parameters:this.sanitizeSchema(n.function.parameters)}))}]),this.thinkingBudget!==void 0&&this.thinkingBudget!==0&&(o.thinkingConfig={thinkingBudget:this.thinkingBudget}),{model:e.model,config:o}}formatHistory(e){let t=e.filter(l=>l.role!=="system");if(t.length===0)return{history:[],lastUserMessage:""};let o=t[t.length-1],n=o.role==="tool"&&!!o.tool_call_id,i=(n?t:t.slice(0,-1)).map(l=>{if(l.role==="tool"&&l.tool_call_id){let p=this.sanitizeToolName(l.name??l.tool_call_id),d=typeof l.content=="string"?l.content:JSON.stringify(l.content),m=d.match(/^data:([\w/+.-]+);base64,(.+)$/s),u=m?null:et(d),b=[{functionResponse:{name:p,response:{name:p,content:m||u?"File data attached as sibling part.":d}}}];return m&&b.push({inlineData:{mimeType:m[1],data:m[2]}}),u&&b.push({fileData:{mimeType:u.mimeType,fileUri:u.url}}),{role:"function",parts:b}}if(l.role==="assistant"&&l.tool_calls&&l.tool_calls.length>0){let p=l.tool_calls.map(u=>u.id).join("|"),d=this.rawContentCache.get(p);if(d)return d;let m=[];typeof l.content=="string"&&l.content&&m.push({text:l.content});for(let u of l.tool_calls)m.push({functionCall:{name:this.sanitizeToolName(u.function.name),args:typeof u.function.arguments=="string"?JSON.parse(u.function.arguments||"{}"):u.function.arguments}});return{role:"model",parts:m}}return{role:l.role==="user"?"user":"model",parts:this.contentToParts(l.content)}}),a=[];for(let l of i){let p=a[a.length-1];l.role==="function"&&p?.role==="function"?p.parts.push(...l.parts):a.push(l)}return{history:a,lastUserMessage:n?null:this.contentToParts(o.content)}}contentToParts(e){return typeof e=="string"?[{text:e}]:e?e.map(t=>{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 l=a.functionCall;o.push({id:`vtx_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,name:this.restoreToolName(l.name,t),arguments:l.args??{}})}}return{content:n,toolCalls:o,rawContent:s}}extractSystemInstruction(e){let t=e.filter(o=>o.role==="system");if(t.length!==0)return t.map(o=>typeof o.content=="string"?o.content:"").join(`
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 ae(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 O(t,e):new F(t||"Vertex AI Error","VERTEXAI_ERROR",e?.status??500,e)}};c();var ac=require("@google/generative-ai"),Xs=require("zod-to-json-schema");le();P();var Dn=class r extends X{genAI;rawContentCache=new Map;static RAW_CONTENT_CACHE_MAX=500;constructor(e){super(),this.genAI=new ac.GoogleGenerativeAI(e)}supportsFileUpload(){return!0}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[o,n]of Object.entries(e))o==="additionalProperties"||o==="exclusiveMinimum"||o==="exclusiveMaximum"||o==="$schema"||o==="$id"||o==="definitions"||o==="$defs"||(typeof n=="object"&&n!==null?Array.isArray(n)?t[o]=n.map(s=>this.sanitizeSchema(s)):t[o]=this.sanitizeSchema(n):t[o]=n);return t}async uploadFile(e){try{let t=await import("fs"),o=await import("path");if(!e.filePath)throw new O("Gemini uploadFile requires a filePath.");let n=await t.promises.readFile(e.filePath),s=o.basename(e.filePath),i=e.mimeType||"application/octet-stream",l=`https://generativelanguage.googleapis.com/upload/v1beta/files?key=${this.genAI.apiKey}`,p="----WebKitFormBoundary"+Math.random().toString(36).substring(2),d=JSON.stringify({file:{displayName:s}}),m=Buffer.concat([Buffer.from(`--${p}\r
457
457
  Content-Type: application/json\r
458
458
  \r
459
459
  ${d}\r
@@ -462,27 +462,27 @@ Content-Type: ${i}\r
462
462
  \r
463
463
  `),n,Buffer.from(`\r
464
464
  --${p}--\r
465
- `)]),f=await fetch(c,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:m});if(!f.ok){let h=await f.text();throw new Error(`Gemini file upload failed: ${f.status} ${h}`)}let b=await f.json();return{id:b.file?.name||b.name,url:b.file?.uri||b.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,o=`https://generativelanguage.googleapis.com/v1beta/${e}?key=${t}`,n=await fetch(o,{method:"DELETE"});if(!n.ok){let s=await n.text();throw new Error(`Gemini file deletion failed: ${n.status} ${s}`)}}catch(t){throw this.handleError(t)}}getDisplayName(){return"Google Gemini"}async getModels(){return[{id:"gemini-3.1-flash-lite-preview",displayName:"Gemini 3.1 Flash-Lite Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0?(o.tools=[{functionDeclarations:e.tools.map(f=>({name:this.sanitizeToolName(f.function.name),description:f.function.description,parameters:this.sanitizeSchema(f.function.parameters)}))}],y(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&y(`[Gemini][${t}] First tool: ${A(e.tools[0],800)}`)):y(`[Gemini][${t}] NO TOOLS in request`),y(`[Gemini][${t}] generate() request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),oe(t,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format)&&!e.tools?.length?"application/json":"text/plain",...e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&!e.tools?.length?{responseSchema:this.sanitizeSchema((0,Js.zodToJsonSchema)(e.response_format))}:{}}}).sendMessage(i)).response,d=[],m="";for(let f of p.candidates||[])for(let b of f.content?.parts||[])if(b.text&&(m+=b.text),b.functionCall){let h=b.functionCall;d.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(h.name,e.tools),arguments:h.args||{}})}if(d.length>0){let f=p.candidates?.[0]?.content;if(f){let b=d.map(h=>h.id).join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(b,f)}}return y(`[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()}`;y(`[Gemini][${o}] Stream request: model=${e.model}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),e.tools&&e.tools.length>0&&y(`[Gemini][${o}] First tool: ${A(e.tools[0],800)}`),oe(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((0,Js.zodToJsonSchema)(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){y(`[Gemini][${o}] Stream finish_reason=tool_calls name=${m.functionCall.name}`);let f=`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`;p.push(f),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:f,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(f=>f.text)&&(yield{delta:m})}catch{}}if(p.length>0)try{let m=(await c.response).candidates?.[0]?.content;if(m){let f=p.join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(f,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
+ `)]),u=await fetch(l,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:m});if(!u.ok){let h=await u.text();throw new Error(`Gemini file upload failed: ${u.status} ${h}`)}let b=await u.json();return{id:b.file?.name||b.name,url:b.file?.uri||b.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,o=`https://generativelanguage.googleapis.com/v1beta/${e}?key=${t}`,n=await fetch(o,{method:"DELETE"});if(!n.ok){let s=await n.text();throw new Error(`Gemini file deletion failed: ${n.status} ${s}`)}}catch(t){throw this.handleError(t)}}getDisplayName(){return"Google Gemini"}async getModels(){return[{id:"gemini-3.1-flash-lite-preview",displayName:"Gemini 3.1 Flash-Lite Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0?(o.tools=[{functionDeclarations:e.tools.map(u=>({name:this.sanitizeToolName(u.function.name),description:u.function.description,parameters:this.sanitizeSchema(u.function.parameters)}))}],y(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&y(`[Gemini][${t}] First tool: ${N(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}`),ne(t,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format)&&!e.tools?.length?"application/json":"text/plain",...e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&!e.tools?.length?{responseSchema:this.sanitizeSchema((0,Xs.zodToJsonSchema)(e.response_format))}:{}}}).sendMessage(i,e.signal?{signal:e.signal}:void 0)).response,d=[],m="";for(let u of p.candidates||[])for(let b of u.content?.parts||[])if(b.text&&(m+=b.text),b.functionCall){let h=b.functionCall;d.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(h.name,e.tools),arguments:h.args||{}})}if(d.length>0){let u=p.candidates?.[0]?.content;if(u){let b=d.map(h=>h.id).join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(b,u)}}return y(`[Gemini][${t}] Response finish_reason=${d.length>0?"tool_calls":"stop"} tool_calls=${d.length} content_preview=${N(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()}`;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: ${N(e.tools[0],800)}`),ne(o,"Gemini",e.messages);let n=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),l=await n.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:(e.response_format==="json_object"||e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format)&&!e.tools?.length?"application/json":"text/plain",...e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&!e.tools?.length?{responseSchema:this.sanitizeSchema((0,Xs.zodToJsonSchema)(e.response_format))}:{}}}).sendMessageStream(i,e.signal?{signal:e.signal}:void 0),p=[];for await(let d of l.stream){for(let m of d.candidates?.[0]?.content?.parts||[])if(m.functionCall){y(`[Gemini][${o}] Stream finish_reason=tool_calls name=${m.functionCall.name}`);let u=`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`;p.push(u),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:u,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(u=>u.text)&&(yield{delta:m})}catch{}}if(p.length>0)try{let m=(await l.response).candidates?.[0]?.content;if(m){let u=p.join("|");this.rawContentCache.size>=r.RAW_CONTENT_CACHE_MAX&&this.rawContentCache.delete(this.rawContentCache.keys().next().value),this.rawContentCache.set(u,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(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(()=>(Ae(),Mt)),a=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async b=>{if(b.type==="text")return{text:b.text};if(b.type==="image_data"||b.type==="image_file"||b.type==="image_url")try{let{data:h,mimeType:T}=await i(b);return{inlineData:{mimeType:T,data:h}}}catch{return b.type==="image_url"?{text:`[Image: ${b.image_url.url}]`}:{text:"[Unresolvable Image]"}}if(b.type==="file"){let h=b.file.url.match(/^data:([\w/+.-]+);base64,(.+)$/s);return h?{inlineData:{mimeType:h[1],data:h[2]}}:{fileData:{fileUri:b.file.url,mimeType:b.file.mimeType}}}return null}))).filter(Boolean),c=await Promise.all(s.map(async m=>{if(m.role==="tool"&&m.tool_call_id){let f=this.sanitizeToolName(m.name||m.tool_call_id),b=typeof m.content=="string"?m.content:JSON.stringify(m.content),h=b.match(/^data:([\w/+.-]+);base64,(.+)$/s),T=[{functionResponse:{name:f,response:{name:f,content:h?"File data attached as sibling part.":b}}}];return h&&T.push({inlineData:{mimeType:h[1],data:h[2]}}),{role:"function",parts:T}}if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let f=m.tool_calls.map(T=>T.id).join("|"),b=this.rawContentCache.get(f);if(b)return b;let h=[];if(typeof m.content=="string"&&m.content)h.push({text:m.content});else if(Array.isArray(m.content)){let T=m.content.filter(k=>typeof k=="object"&&k.type==="text").map(k=>k.text).join(`
468
- `);T&&h.push({text:T})}for(let T of m.tool_calls)h.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:h}}return{role:m.role==="user"?"user":"model",parts:await a(m.content)}})),p=[];for(let m of c){let f=p[p.length-1];m.role==="function"&&f?.role==="function"?f.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 ie(e.message,void 0,e):e.status>=400&&e.status<500?new M(e.message,e):e.message&&e.message.includes("API key")?new ue(e.message,e):new L(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};l();var Ze=x(require("fs"),1),Vs=x(require("path"),1);pe();var sc="toolpack.config.json",jr=new Map;async function ic(r){for(;jr.has(r);)await jr.get(r);let e,t=new Promise(o=>{e=o});return jr.set(r,t),()=>{jr.delete(r),e()}}function gt(r){if(r&&Ze.existsSync(r))return r;let e=Vs.join(process.cwd(),sc);return Ze.existsSync(e)?e:null}function $n(r){if(!r)return null;try{let e=Ze.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function Lr(r){let e=r||gt();return $n(e)||{}}function ac(){}function lc(r){return(Lr(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function En(r){return Lr(r).ollama?.baseUrl||"http://localhost:11434"}async function cc(r){let{type:e,value:t,configPath:o}=r,n=o||gt();n||(n=Vs.join(process.cwd(),sc));let s=await ic(n);try{let i=$n(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{Ze.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new O(`Failed to write bypass rule to config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}}finally{s()}}async function pc(r){let{type:e,value:t,configPath:o}=r,n=o||gt();if(!n)return;let s=await ic(n);try{let i=$n(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{Ze.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new O(`Failed to remove bypass rule from config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}}finally{s()}}l();l();var Xs=require("zod-to-json-schema");pe();_();l();var Qs=x(require("http"),1);function Pe(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=Qs.default.request(c,d=>{let m=[];d.on("data",f=>m.push(f)),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 Fr(r,e,t,o=12e4,n){let s,i=!1;return n&&n.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let 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((f,b)=>{s=Qs.default.request(p,f),s.on("error",b),s.on("timeout",()=>{s.destroy(),b(new Error("Stream request timed out"))}),s.write(JSON.stringify(t)),s.end()});if(d.statusCode&&d.statusCode>=400){let f="";for await(let b of d)f+=b.toString();throw new Error(`Ollama HTTP ${d.statusCode}: ${f}`)}let m="";for await(let f of d){if(i)break;let b=f.toString();if(m+=b,m.includes('"error"'))try{let T=JSON.parse(m.trim());if(T.error)throw new Error(`Ollama: ${T.error}`)}catch(T){if(T.message.startsWith("Ollama:"))throw T}let h=m.split(`
469
- `);m=h.pop()||"";for(let T of h)T.trim()&&(yield T)}m.trim()&&!i&&(yield m.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var et=class extends Q{config;baseUrl;timeout;modelName;constructor(e){super(),this.config=e,this.baseUrl=e.baseUrl||"http://localhost:11434",this.timeout=e.timeout||12e4,this.modelName=e.model}getDisplayName(){return"Ollama"}async getModels(){try{return(await this.listModels()).map(t=>({id:t.name,displayName:t.name,capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!0,vision:!0}}))}catch{return[]}}async connect(){let e=await this.listModels(),t=this.config.model.split(":")[0].toLowerCase();if(!e.some(n=>n.name.split(":")[0].toLowerCase()===t||n.name.toLowerCase()===this.config.model.toLowerCase()))throw new 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 Pe(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 He(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await Pe(this.baseUrl,"/api/tags","GET",void 0,3e3),!0}catch{return!1}}async isModelAvailable(e){try{let t=await this.listModels(),o=(e||this.config.model).toLowerCase(),n=o.split(":")[0];return t.some(s=>s.name.split(":")[0].toLowerCase()===n||s.name.toLowerCase()===o)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await Promise.all(e.messages.map(i=>this.toOllamaMessage(i,e.mediaOptions))),n=e.model||this.config.model,s={model:n,messages:o,stream:!1,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=(0,Xs.zodToJsonSchema)(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] generate() request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),oe(t,"Ollama",e.messages);try{let i=await Pe(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 y(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${c.length} content_preview=${A(p.content,200)}`),p}catch(i){throw i instanceof L?i:new He(`Failed to generate with Ollama model "${n}": ${i.message}`,i)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),n=e.model||this.config.model,s={model:n,messages:o,stream:!0,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=(0,Xs.zodToJsonSchema)(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${A(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] Stream request: model=${n}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),oe(t,"Ollama",e.messages);let{stream:i}=Fr(this.baseUrl,"/api/chat",s,this.timeout,e.signal);try{for await(let a of i)try{let 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||{}}));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){Qe(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new He(`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 Pe(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 He(`Embedding failed for Ollama model "${n}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(Ae(),Mt));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
- `;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}]
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(()=>(Me(),Ot)),a=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async b=>{if(b.type==="text")return{text:b.text};if(b.type==="image_data"||b.type==="image_file"||b.type==="image_url")try{let{data:h,mimeType:T}=await i(b);return{inlineData:{mimeType:T,data:h}}}catch{return b.type==="image_url"?{text:`[Image: ${b.image_url.url}]`}:{text:"[Unresolvable Image]"}}if(b.type==="file"){let h=b.file.url.match(/^data:([\w/+.-]+);base64,(.+)$/s);return h?{inlineData:{mimeType:h[1],data:h[2]}}:{fileData:{fileUri:b.file.url,mimeType:b.file.mimeType}}}return null}))).filter(Boolean),l=await Promise.all(s.map(async m=>{if(m.role==="tool"&&m.tool_call_id){let u=this.sanitizeToolName(m.name||m.tool_call_id),b=typeof m.content=="string"?m.content:JSON.stringify(m.content),h=b.match(/^data:([\w/+.-]+);base64,(.+)$/s),T=[{functionResponse:{name:u,response:{name:u,content:h?"File data attached as sibling part.":b}}}];return h&&T.push({inlineData:{mimeType:h[1],data:h[2]}}),{role:"function",parts:T}}if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let u=m.tool_calls.map(T=>T.id).join("|"),b=this.rawContentCache.get(u);if(b)return b;let h=[];if(typeof m.content=="string"&&m.content)h.push({text:m.content});else if(Array.isArray(m.content)){let T=m.content.filter(C=>typeof C=="object"&&C.type==="text").map(C=>C.text).join(`
468
+ `);T&&h.push({text:T})}for(let T of m.tool_calls)h.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:h}}return{role:m.role==="user"?"user":"model",parts:await a(m.content)}})),p=[];for(let m of l){let u=p[p.length-1];m.role==="function"&&u?.role==="function"?u.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 ae(e.message,void 0,e):e.status>=400&&e.status<500?new O(e.message,e):e.message&&e.message.includes("API key")?new fe(e.message,e):new F(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};c();var tt=x(require("fs"),1),Ys=x(require("path"),1);le();var lc="toolpack.config.json",qr=new Map;async function cc(r){for(;qr.has(r);)await qr.get(r);let e,t=new Promise(o=>{e=o});return qr.set(r,t),()=>{qr.delete(r),e()}}function yt(r){if(r&&tt.existsSync(r))return r;let e=Ys.join(process.cwd(),lc);return tt.existsSync(e)?e:null}function An(r){if(!r)return null;try{let e=tt.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function Wr(r){let e=r||yt();return An(e)||{}}function pc(){}function mc(r){return(Wr(r).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function Mn(r){return Wr(r).ollama?.baseUrl||"http://localhost:11434"}async function dc(r){let{type:e,value:t,configPath:o}=r,n=o||yt();n||(n=Ys.join(process.cwd(),lc));let s=await cc(n);try{let i=An(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{tt.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new M(`Failed to write bypass rule to config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}}finally{s()}}async function uc(r){let{type:e,value:t,configPath:o}=r,n=o||yt();if(!n)return;let s=await cc(n);try{let i=An(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{tt.writeFileSync(n,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new M(`Failed to remove bypass rule from config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}}finally{s()}}c();c();var ei=require("zod-to-json-schema");le();P();c();var Zs=x(require("http"),1);function Re(r,e,t,o,n=12e4,s){return new Promise((i,a)=>{if(s?.aborted)return a(new A);let l=new URL(e,r),p={hostname:l.hostname,port:l.port,path:l.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:n},d=Zs.default.request(p,u=>{let b=[];u.on("data",h=>b.push(h)),u.on("end",()=>{i({status:u.statusCode||0,body:Buffer.concat(b).toString("utf-8")})})}),m=()=>{d.destroy(),a(new A)};s?.addEventListener("abort",m,{once:!0}),d.on("close",()=>s?.removeEventListener("abort",m)),d.on("error",u=>a(u)),d.on("timeout",()=>{d.destroy(),a(new Error("Request timed out"))}),o&&d.write(JSON.stringify(o)),d.end()})}function Ur(r,e,t,o=12e4,n){let s,i=!1;return n&&n.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let l=new URL(e,r),p={hostname:l.hostname,port:l.port,path:l.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},d=await new Promise((u,b)=>{s=Zs.default.request(p,u),s.on("error",b),s.on("timeout",()=>{s.destroy(),b(new Error("Stream request timed out"))}),s.write(JSON.stringify(t)),s.end()});if(d.statusCode&&d.statusCode>=400){let u="";for await(let b of d)u+=b.toString();throw new Error(`Ollama HTTP ${d.statusCode}: ${u}`)}let m="";for await(let u of d){if(i)break;let b=u.toString();if(m+=b,m.includes('"error"'))try{let T=JSON.parse(m.trim());if(T.error)throw new Error(`Ollama: ${T.error}`)}catch(T){if(T.message.startsWith("Ollama:"))throw T}let h=m.split(`
469
+ `);m=h.pop()||"";for(let T of h)T.trim()&&(yield T)}m.trim()&&!i&&(yield m.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var ot=class extends X{config;baseUrl;timeout;modelName;constructor(e){super(),this.config=e,this.baseUrl=e.baseUrl||"http://localhost:11434",this.timeout=e.timeout||12e4,this.modelName=e.model}getDisplayName(){return"Ollama"}async getModels(){try{return(await this.listModels()).map(t=>({id:t.name,displayName:t.name,capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!0,vision:!0}}))}catch{return[]}}async connect(){let e=await this.listModels(),t=this.config.model.split(":")[0].toLowerCase();if(!e.some(n=>n.name.split(":")[0].toLowerCase()===t||n.name.toLowerCase()===this.config.model.toLowerCase()))throw new O(`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 Re(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new F(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof F?e:new Je(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await Re(this.baseUrl,"/api/tags","GET",void 0,3e3),!0}catch{return!1}}async isModelAvailable(e){try{let t=await this.listModels(),o=(e||this.config.model).toLowerCase(),n=o.split(":")[0];return t.some(s=>s.name.split(":")[0].toLowerCase()===n||s.name.toLowerCase()===o)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(n=>this.sanitizeToolName(n.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await Promise.all(e.messages.map(i=>this.toOllamaMessage(i,e.mediaOptions))),n=e.model||this.config.model,s={model:n,messages:o,stream:!1,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=(0,ei.zodToJsonSchema)(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${N(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}`),ne(t,"Ollama",e.messages);try{let i=await Re(this.baseUrl,"/api/chat","POST",s,this.timeout,e.signal);if(i.status!==200)throw this.handleHttpError(i.status,i.body);let a=JSON.parse(i.body),l=[];if(a.message?.tool_calls)for(let d of a.message.tool_calls)l.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:l.length>0?"tool_calls":a.done?"stop":void 0,tool_calls:l.length>0?l:void 0,raw:a};return y(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${l.length} content_preview=${N(p.content,200)}`),p}catch(i){throw i instanceof F?i:new Je(`Failed to generate with Ollama model "${n}": ${i.message}`,i)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),n=e.model||this.config.model,s={model:n,messages:o,stream:!0,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format&&(s.format=(0,ei.zodToJsonSchema)(e.response_format)),e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${N(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}`),ne(t,"Ollama",e.messages);let{stream:i}=Ur(this.baseUrl,"/api/chat",s,this.timeout,e.signal);try{for await(let a of i)try{let l=JSON.parse(a);if(l.message?.content){let p=l.message.tool_calls&&l.message.tool_calls.length>0;yield{delta:l.message.content,finish_reason:l.done&&!p?"stop":void 0,usage:l.done&&l.prompt_eval_count!=null?{prompt_tokens:l.prompt_eval_count||0,completion_tokens:l.eval_count||0,total_tokens:(l.prompt_eval_count||0)+(l.eval_count||0)}:void 0}}if(l.message?.tool_calls&&l.message.tool_calls.length>0){let p=l.message.tool_calls.map(d=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(d.function.name,e.tools),arguments:d.function.arguments||{}}));y(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(l.done&&!l.message?.content&&!l.message?.tool_calls){Ye(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new Je(`Stream failed for Ollama model "${n}": ${a.message}`,a)}}async embed(e){let t=e.__toolpack_request_id||`emb-${Date.now()}`,o=typeof e.input=="string"?[e.input]:e.input,n=e.model||this.config.model;y(`[Ollama][${t}] Embedding request: model=${n}, inputs=${o.length}`);try{let s=await Re(this.baseUrl,"/api/embed","POST",{model:n,input:o},this.timeout);if(s.status!==200)throw this.handleHttpError(s.status,s.body);return{embeddings:JSON.parse(s.body).embeddings||[]}}catch(s){throw s instanceof F?s:new Je(`Embedding failed for Ollama model "${n}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",n=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(Me(),Ot));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
+ `;else if(a.type==="image_url"||a.type==="image_data"||a.type==="image_file")try{let{data:l}=await s(a);n.push(l)}catch{a.type==="image_url"?o+=`[Image: ${a.image_url.url}]
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 L(o,"OLLAMA_ERROR",e)}};l();var Nt=class extends Q{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await Pe(this.baseUrl,"/api/tags","GET",void 0,5e3);if(t.status!==200)return[];e=JSON.parse(t.body).models||[]}catch{return[]}return Promise.all(e.map(t=>this.buildModelInfo(t)))}async generate(e){return this.getAdapterForModel(e.model).generate(this.stripToolsIfNeeded(e))}async*stream(e){yield*this.getAdapterForModel(e.model).stream(this.stripToolsIfNeeded(e))}async embed(e){return this.getAdapterForModel(e.model).embed(e)}async disconnect(){this.adapterCache.clear(),this.capabilityCache.clear()}stripToolsIfNeeded(e){let t=this.capabilityCache.get(e.model);if(t&&!t.toolCalling&&e.tools&&e.tools.length>0){let{tools:o,tool_choice:n,...s}=e,i=s,a={role:"system",content:"You do not have access to any tools or functions. Do not attempt to call tools, output tool invocations, or reference tool usage. Answer the user directly using only your own knowledge."};return i.messages=[...i.messages,a],i}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new et({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,o=!1,n=!1;try{let a=await Pe(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 Pe(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 Ys=[{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 mc(){return Ys[0].model}function dc(r){let e=r.toLowerCase();return Ys.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function uc(){return[...Ys]}l();var Zs=x(require("openai"),1),ei=require("openai/helpers/zod");pe();_();Ae();var ht=class extends Q{client;constructor(e,t){super(),this.client=new Zs.default({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new 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(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?(0,ei.zodResponseFormat)(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 f=this.sanitizeToolName(m.function.name);return s.set(f,m.function.name),{type:"function",function:{name:f,description:m.function.description,parameters:m.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),y(`[OpenAI][${t}] First tool: ${A(n.tools[0],800)}`)),y(`[OpenAI][${t}] Request params: ${A({model:n.model,messages_count:n.messages.length,has_tools:!!n.tools,tools_count:n.tools?.length,tool_choice:n.tool_choice},800)}`),oe(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0);Qe(`[OpenAI][${t}] Raw completion: ${JSON.stringify(i)}`);let a=i.choices[0].message;y(`[OpenAI][${t}] Response: finish_reason=${i.choices[0].finish_reason}`),y(`[OpenAI][${t}] Response has tool_calls: ${!!a.tool_calls}, count: ${a.tool_calls?.length||0}`),y(`[OpenAI][${t}] Response content: ${JSON.stringify(a.content)}`),a.content&&y(`[OpenAI][${t}] Response content preview: ${A(a.content,200)}`);let c=i.choices[0],p,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?(0,ei.zodResponseFormat)(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: ${A(n.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${n.model}, messages=${n.messages.length}, tools=${n.tools?.length||0}, tool_choice=${n.tool_choice??"unset"}`),oe(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0),a=new Map;for await(let c of i){let p=c.choices[0];if(p.finish_reason&&Qe(`[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 f=a.get(m);d.id&&(f.id=d.id),d.function?.name&&(f.name=d.function.name),d.function?.arguments&&(f.args+=d.function.arguments),Qe(`[OpenAI][${t}] tool_call_delta idx=${m} id=${d.id||f.id||""} name=${d.function?.name||f.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||"{}")}));y(`[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:Ye(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(()=>(Ae(),Mt)),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 Zs.default.APIError){let t=e.message;return e.status===401?new ue(t,e):e.status===429?new ie(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new L(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new L("Unknown error","UNKNOWN",500,e)}};l();var fc="https://openrouter.ai/api/v1",Dn=class extends ht{name="openrouter";_apiKey;constructor(e,t={}){super(e,fc),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(`${fc}/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"}};Ae();l();l();var un=class{tools=new Map;projects=new Map;config=te;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(()=>(wc(),Tc));this.runtimeContext=new e;let{fsToolsProject:t}=await Promise.resolve().then(()=>(Ci(),Nm)),{execToolsProject:o}=await Promise.resolve().then(()=>(Mi(),Md)),{systemToolsProject:n}=await Promise.resolve().then(()=>(Ui(),du)),{httpToolsProject:s}=await Promise.resolve().then(()=>(Vi(),Ju)),{githubToolsProject:i}=await Promise.resolve().then(()=>(ia(),Qf)),{webToolsProject:a}=await Promise.resolve().then(()=>(Ta(),gh)),{codingToolsProject:c}=await Promise.resolve().then(()=>(La(),ab)),{gitToolsProject:p,createGitCloneTool:d}=await Promise.resolve().then(()=>(Wa(),qb)),{diffToolsProject:m}=await Promise.resolve().then(()=>(Ba(),eT)),{dbToolsProject:f}=await Promise.resolve().then(()=>(Ja(),PT)),{cloudToolsProject:b}=await Promise.resolve().then(()=>(Qa(),LT)),{slackToolsProject:h}=await Promise.resolve().then(()=>(rl(),xw)),{k8sToolsProject:T}=await Promise.resolve().then(()=>(il(),Sw)),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,f,b,h,T])}};l();var at=x(require("fs"),1),us=x(require("path"),1);_();var _w="toolpack.config.json";function al(r){let e=$w(r);if(!at.existsSync(e))return{};try{let t=at.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Pw(r){let e=al(r),t=NC(e.tools||e);return y(JSON.stringify(t??{})),t}function Rw(r,e){let t=$w(e),o={};try{at.existsSync(t)&&(o=JSON.parse(at.readFileSync(t,"utf-8")))}catch{o={}}o.tools=r,at.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function NC(r){let e=r.additionalConfigurations||{};return e.webSearch||(e.webSearch={}),!e.webSearch.tavilyApiKey&&process.env.TOOLPACK_TAVILY_API_KEY&&(e.webSearch.tavilyApiKey=process.env.TOOLPACK_TAVILY_API_KEY),!e.webSearch.braveApiKey&&process.env.TOOLPACK_BRAVE_API_KEY&&(e.webSearch.braveApiKey=process.env.TOOLPACK_BRAVE_API_KEY),{enabled:r.enabled??te.enabled,autoExecute:r.autoExecute??te.autoExecute,maxToolRounds:r.maxToolRounds??te.maxToolRounds,toolChoicePolicy:r.toolChoicePolicy??te.toolChoicePolicy,resultMaxChars:r.resultMaxChars??te.resultMaxChars,enabledTools:r.enabledTools??te.enabledTools,enabledToolCategories:r.enabledToolCategories??te.enabledToolCategories,toolSearch:r.toolSearch??te.toolSearch,additionalConfigurations:e}}function $w(r){return r?r.endsWith(".json")?us.resolve(r):us.resolve(r,_w):us.resolve(process.cwd(),_w)}l();_();function Ew(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&&N(`[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}}vn();Ci();Mi();Ui();Vi();ia();Ta();La();Wa();Ba();Ja();Qa();il();rl();l();l();var Dw=require("child_process"),Aw=require("events");_();var wr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},Ie=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},fn=class extends Aw.EventEmitter{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async initializeServer(){await this.request("initialize",{client:"toolpack-sdk"})}async connect(){if(this._shuttingDown)throw new Ie("Client is shutting down");if(this.buffer="",this.process=(0,Dw.spawn)(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new Ie("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=>{N(`[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 Ie(`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 Ie("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 wr(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 Ie("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 Ie("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 xr=class{constructor(e){this.config=e}config;clients=new Map;serverConfigs=new Map;toolDefinitions=new Map;toolOwners=new Map;async connectServer(e){let{name:t,displayName:o,toolPrefix:n,...s}=e;S(`[MCP] Connecting to server: ${o||t}`);try{let i=new fn({...s,requestTimeoutMs:s.requestTimeoutMs??this.config.defaultTimeoutMs,autoReconnect:s.autoReconnect??this.config.autoReconnect??!0});this.setupClientEvents(i,t),await i.connect(),this.clients.set(t,i),this.serverConfigs.set(t,e),await this.discoverServerTools(t,i,e)}catch(i){throw fe(`[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){N(`[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 fe(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{fe(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{N(`[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=>{fe(`[MCP] ${t} tool refresh failed after reconnect: ${n}`)})}),e.on("reconnect_failed",o=>{fe(`[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 fs(r){let e=new xr(r);await e.connectAll();let t=e.getToolDefinitions();return{manifest:{key:"mcp-tools",name:"mcp-tools",displayName:"MCP Tools",version:"1.0.0",description:`Tools from ${e.getConnectedServers().length} MCP server(s)`,category:"mcp",author:"Toolpack SDK",tools:t.map(n=>n.name)},tools:t,mcpManager:e}}async function gs(r){"mcpManager"in r&&await r.mcpManager.disconnectAll()}l();var Y=x(require("fs/promises"),1),me=x(require("path"),1);function cl(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 pl(r){let e=r.match(/\[(.*)\]/);return!e||!e[1]?[]:e[1].split(",").map(t=>t.trim().replace(/"/g,"")).filter(Boolean)}function ll(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 St(r,e){let t=r.match(new RegExp(`## ${e}\\n\\n([\\s\\S]*?)(?=\\n## |$)`));return t&&t[1]?t[1].trim():""}async function Mw(r,e){async function t(o){let n;try{n=await Y.readdir(o)}catch{return null}for(let s of n){let i=me.join(o,s),a;try{a=await Y.stat(i)}catch{continue}if(a.isDirectory()){let c=await t(i);if(c)return c}else if(a.isFile()&&s===`${e}.skill.md`)return i}return null}return t(r)}async function OC(r){let e=[];async function t(o){let n;try{n=await Y.readdir(o)}catch{return}for(let s of n){let i=me.join(o,s),a;try{a=await Y.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function IC(r){let{name:e,title:t,description:o,triggers:n,instructions:s,examples:i,tags:a}=r,c=new Date().toISOString(),p=a&&a.length>0?a.map(m=>`"${m}"`).join(", "):"",d=["---",`name: ${e}`,`title: ${t}`,"version: 1.0.0",`updated: ${c}`,`tags: [${p}]`,"---","","## Description","",o,"","## Triggers","",n.map(m=>`- "${m}"`).join(`
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 O(`Model not found: ${o}`):new F(o,"OLLAMA_ERROR",e)}};c();var It=class extends X{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await Re(this.baseUrl,"/api/tags","GET",void 0,5e3);if(t.status!==200)return[];e=JSON.parse(t.body).models||[]}catch{return[]}return Promise.all(e.map(t=>this.buildModelInfo(t)))}async generate(e){return this.getAdapterForModel(e.model).generate(this.stripToolsIfNeeded(e))}async*stream(e){yield*this.getAdapterForModel(e.model).stream(this.stripToolsIfNeeded(e))}async embed(e){return this.getAdapterForModel(e.model).embed(e)}async disconnect(){this.adapterCache.clear(),this.capabilityCache.clear()}stripToolsIfNeeded(e){let t=this.capabilityCache.get(e.model);if(t&&!t.toolCalling&&e.tools&&e.tools.length>0){let{tools:o,tool_choice:n,...s}=e,i=s,a={role:"system",content:"You do not have access to any tools or functions. Do not attempt to call tools, output tool invocations, or reference tool usage. Answer the user directly using only your own knowledge."};return i.messages=[...i.messages,a],i}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new ot({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,o=!1,n=!1;try{let a=await Re(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(a.status===200){let p=(JSON.parse(a.body).details?.families||[]).map(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(l=>s.includes(l))),n||(n=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(l=>s.includes(l)));let i={toolCalling:t,vision:o,embeddings:n};return this.capabilityCache.set(e.name,i),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:n,vision:o}}}async probeToolSupport(e){try{let t=await Re(this.baseUrl,"/api/chat","POST",{model:e,messages:[{role:"user",content:"hi"}],tools:[{type:"function",function:{name:"__probe",description:"probe",parameters:{type:"object",properties:{}}}}],stream:!1},1e4);return t.status>=400?!1:!JSON.parse(t.body).error}catch{return!1}}};c();var ti=[{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 fc(){return ti[0].model}function gc(r){let e=r.toLowerCase();return ti.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function hc(){return[...ti]}c();var oi=x(require("openai"),1),ni=require("openai/helpers/zod");le();P();Me();var bt=class extends X{client;constructor(e,t){super(),this.client=new oi.default({apiKey:e,baseURL:t,timeout:6e4,maxRetries:2})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new O("OpenAI uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"OpenAI"}async getModels(){return[{id:"gpt-4.1-mini",displayName:"GPT-4.1 Mini",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"low"},{id:"gpt-4.1",displayName:"GPT-4.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"medium"},{id:"gpt-5.1",displayName:"GPT-5.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"medium"},{id:"gpt-5.2",displayName:"GPT-5.2",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4",displayName:"GPT-5.4",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"extended",costTier:"premium"}]}sanitizeToolName(e){return e.replace(/\./g,"_")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,n={messages:await Promise.all(e.messages.map(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?(0,ni.zodResponseFormat)(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 u=this.sanitizeToolName(m.function.name);return s.set(u,m.function.name),{type:"function",function:{name:u,description:m.function.description,parameters:m.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: ${N(n.tools[0],800)}`)),y(`[OpenAI][${t}] Request params: ${N({model:n.model,messages_count:n.messages.length,has_tools:!!n.tools,tools_count:n.tools?.length,tool_choice:n.tool_choice},800)}`),ne(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0);Ye(`[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: ${N(a.content,200)}`);let l=i.choices[0],p,d=l.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:l.message.content,usage:i.usage?{prompt_tokens:i.usage.prompt_tokens,completion_tokens:i.usage.completion_tokens,total_tokens:i.usage.total_tokens}:void 0,finish_reason:l.finish_reason,tool_calls:p,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,n={messages:await Promise.all(e.messages.map(l=>this.toOpenAIMessage(l,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:e.response_format&&typeof e.response_format=="object"&&"parse"in e.response_format?(0,ni.zodResponseFormat)(e.response_format,"structured_output"):void 0,stream:!0},s=new Map;e.tools&&e.tools.length>0?(n.tools=e.tools.map(l=>{let p=this.sanitizeToolName(l.function.name);return s.set(p,l.function.name),{type:"function",function:{name:p,description:l.function.description,parameters:l.function.parameters}}}),n.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${n.tools.length} tools with tool_choice: ${n.tool_choice}`),y(`[OpenAI][${t}] First tool: ${N(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"}`),ne(t,"OpenAI",n.messages);let i=await this.client.chat.completions.create(n,e.signal?{signal:e.signal}:void 0),a=new Map;for await(let l of i){let p=l.choices[0];if(p.finish_reason&&Ye(`[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 u=a.get(m);d.id&&(u.id=d.id),d.function?.name&&(u.name=d.function.name),d.function?.arguments&&(u.args+=d.function.arguments),Ye(`[OpenAI][${t}] tool_call_delta idx=${m} id=${d.id||u.id||""} name=${d.function?.name||u.name||""} args_delta=${N(d.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:l.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:l.usage}),p.finish_reason==="tool_calls"&&a.size>0){let d=Array.from(a.values()).map(m=>({id:m.id,name:s.get(m.name)||m.name,arguments:JSON.parse(m.args||"{}")}));y(`[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:et(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(()=>(Me(),Ot)),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 oi.default.APIError){let t=e.message;return e.status===401?new fe(t,e):e.status===429?new ae(t,void 0,e):e.status&&e.status>=400&&e.status<500?new O(t,e):new F(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new F("Unknown error","UNKNOWN",500,e)}};c();var yc="https://openrouter.ai/api/v1",Nn=class extends bt{name="openrouter";_apiKey;constructor(e,t={}){super(e,yc),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(`${yc}/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"}};Me();c();c();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(()=>(Cc(),vc));this.runtimeContext=new e;let{fsToolsProject:t}=await Promise.resolve().then(()=>(_i(),Lm)),{execToolsProject:o}=await Promise.resolve().then(()=>(Ii(),Id)),{systemToolsProject:n}=await Promise.resolve().then(()=>(zi(),gu)),{httpToolsProject:s}=await Promise.resolve().then(()=>(Yi(),Xu)),{githubToolsProject:i}=await Promise.resolve().then(()=>(ca(),Zf)),{webToolsProject:a}=await Promise.resolve().then(()=>(va(),bh)),{codingToolsProject:l}=await Promise.resolve().then(()=>(Wa(),pb)),{gitToolsProject:p,createGitCloneTool:d}=await Promise.resolve().then(()=>(Ba(),Gb)),{diffToolsProject:m}=await Promise.resolve().then(()=>(Ka(),nT)),{dbToolsProject:u}=await Promise.resolve().then(()=>(Xa(),ET)),{cloudToolsProject:b}=await Promise.resolve().then(()=>(Za(),WT)),{slackToolsProject:h}=await Promise.resolve().then(()=>(al(),kw)),{k8sToolsProject:T}=await Promise.resolve().then(()=>(cl(),Rw)),C={...p,tools:p.tools.map(S=>S.name==="git.clone"?d(this.runtimeContext.cloneState):S)};await this.loadProjects([t,o,n,s,i,a,l,C,m,u,b,h,T])}};c();var ct=x(require("fs"),1),hs=x(require("path"),1);P();var $w="toolpack.config.json";function pl(r){let e=Aw(r);if(!ct.existsSync(e))return{};try{let t=ct.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function Ew(r){let e=pl(r),t=jC(e.tools||e);return y(JSON.stringify(t??{})),t}function Dw(r,e){let t=Aw(e),o={};try{ct.existsSync(t)&&(o=JSON.parse(ct.readFileSync(t,"utf-8")))}catch{o={}}o.tools=r,ct.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function jC(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 Aw(r){return r?r.endsWith(".json")?hs.resolve(r):hs.resolve(r,$w):hs.resolve(process.cwd(),$w)}c();P();function Mw(r){if(!r.key||!/^[a-z0-9-]+$/.test(r.key))throw new Error(`Invalid tool project key: "${r.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!r.name.trim())throw new Error("Tool project name cannot be empty.");if(!r.tools||r.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of r.tools){if(!t.name)throw new Error("Tool is missing a name.");if(!t.description)throw new Error(`Tool "${t.name}" is missing a description.`);if(!t.parameters)throw new Error(`Tool "${t.name}" is missing parameters.`);if(typeof t.execute!="function")throw new Error(`Tool "${t.name}" is missing an execute function.`);t.category!==r.category&&I(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${r.category}".`)}let e=r.tools.map(t=>t.name);return{manifest:{key:r.key,name:r.name,displayName:r.displayName,version:r.version,description:r.description,author:r.author,repository:r.repository,category:r.category,tools:e},dependencies:r.dependencies,tools:r.tools}}Sn();_i();Ii();zi();Yi();ca();va();Wa();Ba();Ka();Xa();Za();cl();al();c();c();var Nw=require("child_process"),Ow=require("events");P();var Cr=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},hn=class extends Ow.EventEmitter{constructor(t){super();this.config=t;this.defaultTimeoutMs=t.requestTimeoutMs??3e4,this.autoReconnect=t.autoReconnect??!1,this.maxReconnectAttempts=t.maxReconnectAttempts??3,this.reconnectDelayMs=t.reconnectDelayMs??1e3}config;process=null;messageQueue=new Map;nextId=1;buffer="";_connected=!1;_shuttingDown=!1;_reconnectAttempts=0;defaultTimeoutMs;autoReconnect;maxReconnectAttempts;reconnectDelayMs;get connected(){return this._connected&&this.process!==null}async initializeServer(){await this.request("initialize",{client:"toolpack-sdk"})}async connect(){if(this._shuttingDown)throw new Le("Client is shutting down");if(this.buffer="",this.process=(0,Nw.spawn)(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new 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=>{I(`[MCP server stderr] ${t.toString().trim()}`)}),this.process.on("error",t=>{this._connected=!1,this.emit("error",t)}),this.process.on("exit",t=>{let o=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new 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((l,p)=>{let d;i>0&&(d=setTimeout(()=>{let m=this.messageQueue.get(s);m&&(this.messageQueue.delete(s),m.reject(new Cr(t,i)))},i)),this.messageQueue.set(s,{resolve:l,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()}};P();var kr=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;k(`[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 ge(`[MCP] Failed to connect to ${t}: ${i}`),i}}async connectAll(){let e=this.config.servers.filter(t=>t.autoConnect!==!1).map(t=>this.connectServer(t));await Promise.allSettled(e)}async disconnectServer(e){let t=this.clients.get(e);if(!t){I(`[MCP] Server ${e} not found`);return}k(`[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{k(`[MCP] Executing ${e.name} on ${t}`);let a=await n.callTool(e.name,i);return JSON.stringify(a)}catch(a){throw ge(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{ge(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{I(`[MCP] ${t} closed with code ${o}`)}),e.on("reconnecting",({attempt:o,max:n})=>{k(`[MCP] ${t} reconnecting (${o}/${n})`)}),e.on("reconnected",({attempt:o})=>{k(`[MCP] ${t} reconnected after ${o} attempts`),this.refreshServerTools(t).catch(n=>{ge(`[MCP] ${t} tool refresh failed after reconnect: ${n}`)})}),e.on("reconnect_failed",o=>{ge(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{k(`[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||[];k(`[MCP] Discovered ${s.length} tools from ${e}`),this.removeServerToolDefinitions(e);let i=o.toolPrefix||`mcp.${e}.`;for(let a of s){let l=this.convertMcpTool(a,e,i,t);this.toolDefinitions.set(l.name,l),this.toolOwners.set(l.name,e)}}async refreshServerTools(e){let t=this.clients.get(e),o=this.serverConfigs.get(e);!t||!o||await this.discoverServerTools(e,t,o)}};async function ys(r){let e=new kr(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 bs(r){"mcpManager"in r&&await r.mcpManager.disconnectAll()}c();var Z=x(require("fs/promises"),1),de=x(require("path"),1);function dl(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 ul(r){let e=r.match(/\[(.*)\]/);return!e||!e[1]?[]:e[1].split(",").map(t=>t.trim().replace(/"/g,"")).filter(Boolean)}function ml(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 Iw(r,e){async function t(o){let n;try{n=await Z.readdir(o)}catch{return null}for(let s of n){let i=de.join(o,s),a;try{a=await Z.stat(i)}catch{continue}if(a.isDirectory()){let l=await t(i);if(l)return l}else if(a.isFile()&&s===`${e}.skill.md`)return i}return null}return t(r)}async function FC(r){let e=[];async function t(o){let n;try{n=await Z.readdir(o)}catch{return}for(let s of n){let i=de.join(o,s),a;try{a=await Z.stat(i)}catch{continue}a.isDirectory()?await t(i):a.isFile()&&s.endsWith(".skill.md")&&e.push(i)}}return await t(r),e}function qC(r){let{name:e,title:t,description:o,triggers:n,instructions:s,examples:i,tags:a}=r,l=new Date().toISOString(),p=a&&a.length>0?a.map(m=>`"${m}"`).join(", "):"",d=["---",`name: ${e}`,`title: ${t}`,"version: 1.0.0",`updated: ${l}`,`tags: [${p}]`,"---","","## Description","",o,"","## Triggers","",n.map(m=>`- "${m}"`).join(`
478
478
  `),"","## Instructions","",s,""];return i&&d.push("## Examples","",i,""),d.join(`
479
- `)}function jC(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 Y.mkdir(d,{recursive:!0});let m=me.join(d,`${t}.skill.md`);try{return await Y.access(m),JSON.stringify({error:"skill_exists",message:`Skill "${t}" already exists at ${m}. Use skill.update to modify it.`},null,2)}catch{}let f=IC({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:c});return await Y.writeFile(m,f,"utf-8"),JSON.stringify({success:!0,skill:t,path:m,message:`Skill "${o}" created successfully`},null,2)}}}function LC(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 Mw(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 Y.readFile(n,"utf-8")).replace(/\r\n/g,`
480
- `),i=cl(s),a={name:i.name||t,title:i.title||t,version:i.version,tags:i.tags?pl(i.tags):[],updated:i.updated,path:n};return JSON.stringify(o==="metadata"?{skill:t,metadata:a}:o==="description"?{skill:t,description:St(s,"Description")}:o==="triggers"?{skill:t,triggers:ll(s)}:o==="instructions"?{skill:t,instructions:St(s,"Instructions")}:o==="examples"?{skill:t,examples:St(s,"Examples")}:{skill:t,path:n,metadata:a,description:St(s,"Description"),triggers:ll(s),instructions:St(s,"Instructions"),examples:St(s,"Examples")||void 0},null,2)}}}function FC(r){return{name:"skill.update",displayName:"Update Skill",description:"Update fields of an existing skill. Only provided fields are changed.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:"Skill name to update."},title:{type:"string",description:"New title (optional)."},description:{type:"string",description:"New description replacing the existing one (optional)."},triggers:{type:"array",items:{type:"string"},description:"New triggers list replacing the existing one (optional)."},instructions:{type:"string",description:"New instructions replacing the existing ones (optional)."},addExamples:{type:"string",description:"Additional examples text to append to the Examples section (optional)."},addTags:{type:"array",items:{type:"string"},description:"Tags to add to the existing tags (optional)."}},required:["name"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers,i=e.instructions,a=e.addExamples,c=e.addTags,p=await Mw(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 Y.readFile(p,"utf-8")).replace(/\r\n/g,`
481
- `),m=cl(d),f=m.tags?pl(m.tags):[],b=m.title||t,h=m.version||"1.0.0",T=o??b,k=c?[...new Set([...f,...c])]:f,C=new Date().toISOString();if(n!==void 0&&(d=d.replace(/## Description\n\n[\s\S]*?(?=\n## )/,`## Description
479
+ `)}function WC(r){return{name:"skill.create",displayName:"Create Skill",description:"Create a new .skill.md file in the skill library.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:'Skill name in kebab-case (e.g. "code-review"). Used as the filename.'},title:{type:"string",description:"Human-readable title for the skill (max 100 chars)."},description:{type:"string",description:"Short description for BM25 search indexing (max 300 chars)."},triggers:{type:"array",items:{type:"string"},description:"List of trigger phrases that activate this skill (min 1, max 10)."},instructions:{type:"string",description:"Behavioral instructions injected into context when the skill activates (max 2000 chars)."},examples:{type:"string",description:"Optional examples section (max 3000 chars, never auto-injected)."},tags:{type:"array",items:{type:"string"},description:"Optional tags for filtering and search (max 10)."},subfolder:{type:"string",description:'Optional subfolder within the skills directory (e.g. "coding").'}},required:["name","title","description","triggers","instructions"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers??[],i=e.instructions,a=e.examples,l=e.tags??[],p=e.subfolder;if(!/^[a-z][a-z0-9-]*$/.test(t))return JSON.stringify({error:"invalid_name",message:"Skill name must be kebab-case (lowercase letters, numbers, hyphens, starting with a letter)"},null,2);let d=p?de.join(r,p):r;await Z.mkdir(d,{recursive:!0});let m=de.join(d,`${t}.skill.md`);try{return await Z.access(m),JSON.stringify({error:"skill_exists",message:`Skill "${t}" already exists at ${m}. Use skill.update to modify it.`},null,2)}catch{}let u=qC({name:t,title:o,description:n,triggers:s,instructions:i,examples:a,tags:l});return await Z.writeFile(m,u,"utf-8"),JSON.stringify({success:!0,skill:t,path:m,message:`Skill "${o}" created successfully`},null,2)}}}function UC(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 Iw(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 Z.readFile(n,"utf-8")).replace(/\r\n/g,`
480
+ `),i=dl(s),a={name:i.name||t,title:i.title||t,version:i.version,tags:i.tags?ul(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:ml(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:ml(s),instructions:Pt(s,"Instructions"),examples:Pt(s,"Examples")||void 0},null,2)}}}function GC(r){return{name:"skill.update",displayName:"Update Skill",description:"Update fields of an existing skill. Only provided fields are changed.",category:"skills",parameters:{type:"object",properties:{name:{type:"string",description:"Skill name to update."},title:{type:"string",description:"New title (optional)."},description:{type:"string",description:"New description replacing the existing one (optional)."},triggers:{type:"array",items:{type:"string"},description:"New triggers list replacing the existing one (optional)."},instructions:{type:"string",description:"New instructions replacing the existing ones (optional)."},addExamples:{type:"string",description:"Additional examples text to append to the Examples section (optional)."},addTags:{type:"array",items:{type:"string"},description:"Tags to add to the existing tags (optional)."}},required:["name"]},async execute(e){let t=e.name,o=e.title,n=e.description,s=e.triggers,i=e.instructions,a=e.addExamples,l=e.addTags,p=await Iw(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 Z.readFile(p,"utf-8")).replace(/\r\n/g,`
481
+ `),m=dl(d),u=m.tags?ul(m.tags):[],b=m.title||t,h=m.version||"1.0.0",T=o??b,C=l?[...new Set([...u,...l])]:u,S=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 v=s.map(P=>`- "${P}"`).join(`
485
+ `)),s!==void 0){let v=s.map(_=>`- "${_}"`).join(`
486
486
  `);d=d.replace(/## Triggers\n\n[\s\S]*?(?=\n## )/,`## Triggers
487
487
 
488
488
  ${v}
@@ -491,20 +491,20 @@ ${v}
491
491
 
492
492
  ${i}
493
493
 
494
- `)),a){let v=d.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if(v){let P=v[1]??"",E=P.trim()?`
494
+ `)),a){let v=d.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/);if(v){let _=v[1]??"",E=_.trim()?`
495
495
 
496
496
  `:"";d=d.replace(/## Examples\n\n[\s\S]*?(?=\n## |$)/,`## Examples
497
497
 
498
- ${P}${E}${a}
498
+ ${_}${E}${a}
499
499
 
500
500
  `)}else d=d.trimEnd()+`
501
501
 
502
502
  ## Examples
503
503
 
504
504
  ${a}
505
- `}d=d.replace(/^---\n[\s\S]*?\n---/,["---",`name: ${t}`,`title: ${T}`,`version: ${h}`,`updated: ${C}`,`tags: [${k.map(v=>`"${v}"`).join(", ")}]`,"---"].join(`
506
- `)),await Y.writeFile(p,d,"utf-8");let w=[];return o&&w.push("title"),n!==void 0&&w.push("description"),s!==void 0&&w.push("triggers"),i!==void 0&&w.push("instructions"),a&&w.push("examples (appended)"),c&&w.push(`tags (+${c.length})`),JSON.stringify({success:!0,skill:t,path:p,updated:w,message:`Skill "${t}" updated successfully`},null,2)}}}function qC(r){return{name:"skill.list",displayName:"List Skills",description:"List all skills in the skill library, optionally filtered by tag.",category:"skills",parameters:{type:"object",properties:{tag:{type:"string",description:"Filter skills by tag (optional)."},verbose:{type:"boolean",description:"Include description and triggers in the output (default: false).",default:!1}},required:[]},async execute(e){let t=e.tag,o=e.verbose??!1;try{await Y.access(r)}catch{return JSON.stringify({skills:[],count:0,message:"No skills directory found. Use skill.create to create your first skill."},null,2)}let n=await OC(r);if(n.length===0)return JSON.stringify({skills:[],count:0,message:"No skills found. Use skill.create to create your first skill."},null,2);let s=[];for(let i of n){let a=(await Y.readFile(i,"utf-8")).replace(/\r\n/g,`
507
- `),c=cl(a),p=c.name||me.basename(i,".skill.md"),d=c.title||p,m=c.tags?pl(c.tags):[];if(t&&!m.includes(t))continue;let f=me.dirname(me.relative(r,i)),b=f==="."?void 0:f.split(me.sep)[0];o?s.push({name:p,title:d,tags:m,category:b,description:St(a,"Description")||void 0,triggers:ll(a)}):s.push({name:p,title:d})}return JSON.stringify({skills:s,count:s.length,filtered:t?`by tag: ${t}`:null},null,2)}}}function Nw(r){let e=me.resolve(r?.dir??".toolpack/skills"),t=[jC(e),LC(e),FC(e),qC(e)];return{manifest:{key:"skill",name:"skill-tools",displayName:"Skill Management",version:"1.0.0",description:"Tools for creating, reading, updating, and listing agent skill files.",tools:["skill.create","skill.read","skill.update","skill.list"],category:"skills"},tools:t}}l();l();l();l();var hs=`
505
+ `}d=d.replace(/^---\n[\s\S]*?\n---/,["---",`name: ${t}`,`title: ${T}`,`version: ${h}`,`updated: ${S}`,`tags: [${C.map(v=>`"${v}"`).join(", ")}]`,"---"].join(`
506
+ `)),await Z.writeFile(p,d,"utf-8");let w=[];return o&&w.push("title"),n!==void 0&&w.push("description"),s!==void 0&&w.push("triggers"),i!==void 0&&w.push("instructions"),a&&w.push("examples (appended)"),l&&w.push(`tags (+${l.length})`),JSON.stringify({success:!0,skill:t,path:p,updated:w,message:`Skill "${t}" updated successfully`},null,2)}}}function BC(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 Z.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 FC(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 Z.readFile(i,"utf-8")).replace(/\r\n/g,`
507
+ `),l=dl(a),p=l.name||de.basename(i,".skill.md"),d=l.title||p,m=l.tags?ul(l.tags):[];if(t&&!m.includes(t))continue;let u=de.dirname(de.relative(r,i)),b=u==="."?void 0:u.split(de.sep)[0];o?s.push({name:p,title:d,tags:m,category:b,description:Pt(a,"Description")||void 0,triggers:ml(a)}):s.push({name:p,title:d})}return JSON.stringify({skills:s,count:s.length,filtered:t?`by tag: ${t}`:null},null,2)}}}function Lw(r){let e=de.resolve(r?.dir??".toolpack/skills"),t=[WC(e),UC(e),GC(e),BC(e)];return{manifest:{key:"skill",name:"skill-tools",displayName:"Skill Management",version:"1.0.0",description:"Tools for creating, reading, updating, and listing agent skill files.",tools:["skill.create","skill.read","skill.update","skill.list"],category:"skills"},tools:t}}c();c();c();c();var Ts=`
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
- `,WC={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},ml={name:"Agent",planning:{enabled:!0,planningPrompt:hs},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},Ow=`
533
+ `,zC={name:"Direct",planning:{enabled:!1},progress:{enabled:!0}},fl={name:"Agent",planning:{enabled:!0,planningPrompt:Ts},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},jw=`
534
534
  Create a step-by-step plan for this coding task.
535
535
 
536
536
  Rules:
@@ -553,16 +553,16 @@ JSON Schema:
553
553
  }
554
554
  ]
555
555
  }
556
- `,dl={name:"Coding",planning:{enabled:!0,planningPrompt:Ow},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},ul={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var fl={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:ml,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},gl={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:ul,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},hl={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:dl,toolSearch:{alwaysLoadedTools:["coding.read_code","coding.search_code","fs.read_file","fs.write_file","fs.list_dir","skill.search","skill.read","web.search","web.fetch"]}},vr=[fl,hl,gl],_t="chat";var gn=class{modes=new Map;orderedNames=[];constructor(){for(let e of vr)this.register(e)}register(e){if(!e.name||typeof e.name!="string")throw new Error("ModeConfig.name is required and must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("ModeConfig.displayName is required and must be a non-empty string");if(typeof e.systemPrompt!="string")throw new Error("ModeConfig.systemPrompt must be a string (can be empty for passthrough)");if(e.blockAllTools!==void 0&&typeof e.blockAllTools!="boolean")throw new Error("ModeConfig.blockAllTools must be a boolean");let t=["allowedToolCategories","blockedToolCategories","allowedTools","blockedTools"];for(let n of t)if(e[n]!==void 0&&!Array.isArray(e[n]))throw new Error(`ModeConfig.${n} must be an array`);let o=this.modes.has(e.name);this.modes.set(e.name,e),o||this.orderedNames.push(e.name)}get(e){return this.modes.get(e)}has(e){return this.modes.has(e)}getAll(){let e=[];for(let t of this.orderedNames){let o=this.modes.get(t);o&&e.push(o)}return e}getNames(){return[...this.orderedNames]}getDefault(){let e=this.modes.get(_t);if(!e)throw new Error(`Default mode "${_t}" not found in registry`);return e}getNext(e){let t=this.orderedNames.indexOf(e),o=t===-1?0:(t+1)%this.orderedNames.length,n=this.orderedNames[o],s=this.modes.get(n);if(!s)throw new Error(`Mode "${n}" not found in registry`);return s}get size(){return this.modes.size}remove(e){if(vr.some(n=>n.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(n=>n!==e)),o}};l();function Iw(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 ys={planning:{enabled:!1},progress:{enabled:!0}};l();_();var UC=hs,hn=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||UC,n=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);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),d=this.parsePlan(p.content||"",e,p);return S(`[Planner] createPlan() succeeded plan.id=${d.id} steps=${d.steps.length}`),d}catch(p){return N(`[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&&N(`[Planner] parsePlan() truncated ${n.steps.length} steps to maxSteps=${s}`),y(`[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 N(`[Planner] parsePlan() failed: ${n.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){N("[Planner] createFallbackPlan() \u2014 creating single-step fallback due to plan generation failure");let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}-fallback`,request:t,summary:"Fallback single-step plan due to generation failure",steps:[{id:"step-1",number:1,description:"Execute the user request",status:"pending",expectedTools:[],dependsOn:[]}],status:"draft",createdAt:new Date}}};l();var jw=require("events");_();var Cr=class extends jw.EventEmitter{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new At,this.planner=new hn(e,t.planning)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new hn(this.client,e.planning)}shouldRouteSimpleQuery(e){if(!this.config.complexityRouting?.enabled)return!1;let t=this.config.complexityRouting.strategy??"single-step";if(t==="disabled")return!1;let o=mt(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){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);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",N(`[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 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),y(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
556
+ `,gl={name:"Coding",planning:{enabled:!0,planningPrompt:jw},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},hl={name:"Chat",planning:{enabled:!1},progress:{enabled:!1}};var yl={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:fl,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},bl={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:hl,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},Tl={name:"coding",displayName:"Coding",description:"Concise coding mode \u2014 minimal text, focused on file operations and code changes",systemPrompt:["Coding assistant. Use tools to modify code.","Be concise. No conversational filler.","Show code changes clearly."].join(" "),allowedToolCategories:[],blockedToolCategories:[],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!0,includeToolCategories:!0},workflow:gl,toolSearch:{alwaysLoadedTools:["coding.read_code","coding.search_code","fs.read_file","fs.write_file","fs.list_dir","skill.search","skill.read","web.search","web.fetch"]}},Sr=[yl,Tl,bl],Rt="chat";var yn=class{modes=new Map;orderedNames=[];constructor(){for(let e of Sr)this.register(e)}register(e){if(!e.name||typeof e.name!="string")throw new Error("ModeConfig.name is required and must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("ModeConfig.displayName is required and must be a non-empty string");if(typeof e.systemPrompt!="string")throw new Error("ModeConfig.systemPrompt must be a string (can be empty for passthrough)");if(e.blockAllTools!==void 0&&typeof e.blockAllTools!="boolean")throw new Error("ModeConfig.blockAllTools must be a boolean");let t=["allowedToolCategories","blockedToolCategories","allowedTools","blockedTools"];for(let n of t)if(e[n]!==void 0&&!Array.isArray(e[n]))throw new Error(`ModeConfig.${n} must be an array`);let o=this.modes.has(e.name);this.modes.set(e.name,e),o||this.orderedNames.push(e.name)}get(e){return this.modes.get(e)}has(e){return this.modes.has(e)}getAll(){let e=[];for(let t of this.orderedNames){let o=this.modes.get(t);o&&e.push(o)}return e}getNames(){return[...this.orderedNames]}getDefault(){let e=this.modes.get(Rt);if(!e)throw new Error(`Default mode "${Rt}" not found in registry`);return e}getNext(e){let t=this.orderedNames.indexOf(e),o=t===-1?0:(t+1)%this.orderedNames.length,n=this.orderedNames[o],s=this.modes.get(n);if(!s)throw new Error(`Mode "${n}" not found in registry`);return s}get size(){return this.modes.size}remove(e){if(Sr.some(n=>n.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(n=>n!==e)),o}};c();function Fw(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}}c();var ws={planning:{enabled:!1},progress:{enabled:!0}};c();P();var HC=Ts,bn=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||HC,n=e.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[obj]").join(" ").substring(0,100);y(`[Planner] createPlan() provider=${t??"default"} maxSteps=${this.config?.maxSteps??20} request="${n}..."`);let s=e.messages.filter(p=>p.role==="system"),i=e.messages.filter(p=>p.role!=="system"),a=[{role:"system",content:o},...s,...i],l={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:a};try{let p=await this.client.generate(l,t),d=this.parsePlan(p.content||"",e,p);return k(`[Planner] createPlan() succeeded plan.id=${d.id} steps=${d.steps.length}`),d}catch(p){return I(`[Planner] createPlan() failed, using fallback: ${p.message}`),this.createFallbackPlan(e)}}parsePlan(e,t,o){try{let n=JSON.parse(e);if(!n.summary||!Array.isArray(n.steps))throw new Error("Invalid plan structure: missing summary or steps array");let s=this.config?.maxSteps??20,i=n.steps.slice(0,s);n.steps.length>s&&I(`[Planner] parsePlan() truncated ${n.steps.length} steps to maxSteps=${s}`),y(`[Planner] parsePlan() parsed ${i.length} steps successfully`);let a=i.map((p,d)=>({id:`step-${Date.now()}-${d}`,number:p.number||d+1,description:p.description||"Unknown step",expectedTools:p.expectedTools||[],dependsOn:p.dependsOn||[],status:"pending"})),l=t.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}`,request:l,summary:n.summary,steps:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(n){return I(`[Planner] parsePlan() failed: ${n.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){I("[Planner] createFallbackPlan() \u2014 creating single-step fallback due to plan generation failure");let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}-fallback`,request:t,summary:"Fallback single-step plan due to generation failure",steps:[{id:"step-1",number:1,description:"Execute the user request",status:"pending",expectedTools:[],dependsOn:[]}],status:"draft",createdAt:new Date}}};c();var qw=require("events");P();var _r=class extends qw.EventEmitter{client;config;planner;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new Nt,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=ut(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){k(`[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 k(`[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}};k(`[Workflow] Plan "${n.id}" approved`)}return n.status="approved",this.executePlanDirect(n,e,t)}async executeDirect(e,t){let o=Date.now(),n=this.createDummyPlan(e);y(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(n,"executing","Direct execution");let s=await this.client.generate(e,t);n.status="completed",n.completedAt=new Date,n.steps[0].status="completed";let i=Date.now()-o;y(`[Workflow] executeDirect() completed in ${i}ms content_len=${s.content?.length??0}`);let a={success:!0,plan:n,output:s.content||void 0,response:s,metrics:{totalDuration:Date.now()-o,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",n,a),this.emitProgress(n,"completed","Done"),a}catch(s){n.status="failed",n.completedAt=new Date,n.steps[0].status="failed",I(`[Workflow] executeDirect() failed: ${s.message}`);let i={success:!1,plan:n,error:s.message,metrics:{totalDuration:Date.now()-o,stepsCompleted:0,stepsFailed:1,retriesUsed:0}};return this.emit("workflow:failed",n,s),this.emitProgress(n,"failed","Execution failed"),i}}async createPlan(e,t){y(`[Workflow] createPlan() provider=${t??"default"}`);let o=this.createDummyPlan(e);o.status="draft",this.emitProgress(o,"planning","Creating plan...");let n=await this.planner.createPlan(e,t);return k(`[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=`
557
557
  You have created the following plan to fulfill the request:
558
558
  Summary: ${e.summary}
559
559
 
560
560
  Steps:
561
- ${e.steps.map(c=>`${c.number}. ${c.description}`).join(`
561
+ ${e.steps.map(l=>`${l.number}. ${l.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(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),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,N(`[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 l=await this.client.generate(a,o);e.steps.forEach(d=>{d.status="completed",d.result={success:!0,output:l.content||"",response:l}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,n,0),y(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-n}ms`);let p={success:!0,plan:e,output:l.content||void 0,response:l,metrics:e.metrics};return this.emit("workflow:completed",e,p),this.emitProgress(e,"completed","Done"),p}catch(l){e.status="failed",e.completedAt=new Date,I(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${l.message}`);let p={success:!1,plan:e,error:l.message,metrics:this.computeMetrics(e,n,0)};return this.emit("workflow:failed",e,l),this.emitProgress(e,"failed","Execution failed"),p}}emitProgress(e,t,o,n){if(!this.config.progress?.enabled)return;let s=e.steps.length,i=e.steps.filter(p=>p.status==="completed"||p.status==="skipped").length,a=n??(s>0?Math.round(i/s*100):0),l={planId:e.id,currentStep:Math.min(i+1,s),totalSteps:s,percentage:a,currentStepDescription:o??e.steps[i]?.description??"Done",status:t??"executing"};this.emit("workflow:progress",l)}computeMetrics(e,t,o){return{totalDuration:Date.now()-t,stepsCompleted:e.steps.filter(n=>n.status==="completed").length,stepsFailed:e.steps.filter(n=>n.status==="failed").length,retriesUsed:o}}createDummyPlan(e){let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Object]").join(`
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
  ---
@@ -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();var wl=require("events");_();var xl=class r extends wl.EventEmitter{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 Cr(this.client,ys,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){Bl(e.logging);let t=new un,o={...te,...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 fs(s);n=v,await t.loadProjects([v]),S(`[MCP] Loaded ${v.tools.length} tools from MCP servers`)}catch(v){fe(`[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 gn;if(e.customModes)for(let v of e.customModes)m.register(v);let f={...e.hitl||{}};e.confirmationMode!==void 0&&(f.confirmationMode=e.confirmationMode),f.enabled===void 0&&e.onToolConfirm&&(f.enabled=!0),f.confirmationMode===void 0&&e.onToolConfirm&&(f.confirmationMode="all");let b=new kn({providers:c,defaultProvider:d,toolRegistry:t,toolsConfig:t.getConfig(),disableBaseContext:i,disableToolGuidance:a,hitlConfig:Object.keys(f).length>0?f:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow,actor:e.actor}),h=new r(b,d,m),T=e.knowledge,k=T==null?[]:Array.isArray(T)?T:[T];h.knowledgeLayers=k.filter(v=>!!v&&typeof v.toTool=="function"),h.registerRequestTools(h._buildKnowledgeRequestTools()),h.customProviderNames=p,h.mcpToolProject=n,h._interceptors=e.interceptors??[];for(let v of h._interceptors)v.init&&await v.init();let C=e.defaultMode||_t,w=m.get(C);return w&&(b.setMode(w),w.workflow&&h.workflowExecutor.setConfig(w.workflow)),h}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new Pn({projectId:t.projectId,location:t.location,googleAuthOptions:t.googleAuthOptions,thinkingBudget:t.thinkingBudget});if(e==="anthropic-vertex")return new _n({projectId:t.projectId,region:t.region});if(["openai","anthropic","gemini","openrouter"].includes(e)){let s=`TOOLPACK_${e.toUpperCase()}_KEY`,i=t.apiKey||process.env[s]||process.env[`${e.toUpperCase()}_API_KEY`];if(!i){if(n)return null;throw new Error(`No API key found for '${e}'. Set ${s} or pass apiKey in config.`)}switch(e){case"openai":return new ht(i,t.baseUrl);case"anthropic":return new Sn(i,t.baseUrl);case"gemini":return new Rn(i);case"openrouter":return new Dn(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new Nt({baseUrl:t.baseUrl||En(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||En(o);return new et({model:s,baseUrl:i})}throw new Error(`Unknown provider type: ${e}`)}async generate(e,t){let o;if(typeof e=="string"?o={messages:[{role:"user",content:e}],model:""}:o=e,o=this.prepareRequest(o),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 f=m.result.response.usage;i+=f.prompt_tokens,a+=f.completion_tokens||0,c+=f.total_tokens,p.steps.push({stepNumber:m.number,description:m.description,usage:f})}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||gt();if(t)try{let o=$n(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){N(`[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 gs(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){N(`[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(()=>(Vw(),Jw))).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(ys),t}getMode(){return this.client.getMode()}getActiveModeName(){let e=this.client.getMode();return e?e.displayName:"Default"}getModes(){return this.modeRegistry.getAll()}cycleMode(){let e=this.client.getMode(),t=e?e.name:"default",o=this.modeRegistry.getNext(t);return this.client.setMode(o),o}registerMode(e){this.modeRegistry.register(e)}forwardEvents(e){e instanceof wl.EventEmitter&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,o)=>this.emit("workflow:completed",t,o)),e.on("workflow:failed",(t,o)=>this.emit("workflow:failed",t,o))}};l();l();l();var ws=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 xs=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new ws(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 f=Math.ceil(m.content.length/4);if(p.length>0&&d+f>a)break;p.push(m),d+=f}return p}async deleteMessages(e,t){let o=this.lru.get(e);if(!o||t.length===0)return;let n=new Set(t),s=o.filter(i=>!n.has(i.id));this.lru.set(e,s)}clearConversation(e){this.lru.set(e,[])}get conversationCount(){return this.lru.size}};l();var Qw=x(require("better-sqlite3"),1),yn=x(require("fs"),1),kr=x(require("path"),1);function KC(){let r=kr.join(process.cwd(),".toolpack","db","conversation");return yn.existsSync(r)||yn.mkdirSync(r,{recursive:!0}),kr.join(r,"conversation.sqlite")}var vs=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??KC(),o=kr.dirname(t);if(yn.existsSync(o)||yn.mkdirSync(o,{recursive:!0}),this.db=new Qw.default(t),e.enableWAL!==!1){try{this.db.pragma("journal_mode = WAL")}catch{}try{this.db.pragma("synchronous = NORMAL")}catch{}}this.useFTS=e.useFTS===!0,this.maxMessagesPerConversation=e.maxMessagesPerConversation??500,this.initSchema()}initSchema(){this.db.exec(`
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))}};c();var Cl=require("events");P();var kl=class r extends Cl.EventEmitter{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 _r(this.client,ws,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}_buildKnowledgeRequestTools(){return this.knowledgeLayers.length===0?[]:this.knowledgeLayers.length===1?[this.knowledgeLayers[0].toTool(),{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async s=>({success:!0,id:await this.knowledgeLayers[0].add(s.content,s.metadata),message:"Content added to knowledge base successfully."})}]:[{name:"knowledge_search",displayName:"Knowledge Search",description:`Search across ${this.knowledgeLayers.length} knowledge layers for relevant information.`,category:"search",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Search query to find relevant information"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"},threshold:{type:"number",description:"Minimum similarity threshold 0-1 (default: 0.7)"},filter:{type:"object",description:"Optional metadata filters"}},required:["query"]},execute:async o=>{let s=(await Promise.all(this.knowledgeLayers.map(async(a,l)=>(await a.toTool().execute({query:o.query,limit:o.limit,threshold:o.threshold,filter:o.filter})).map(m=>({...m,_layer:l}))))).flat();s.sort((a,l)=>(l.score??0)-(a.score??0));let i=o.limit??10;return s.slice(0,i)}},{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the primary knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async o=>({success:!0,id:await this.knowledgeLayers[0].add(o.content,o.metadata),message:"Content added to knowledge base successfully."})}]}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){Kl(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{k("[MCP] Initializing MCP tool integration");let v=await ys(s);n=v,await t.loadProjects([v]),k(`[MCP] Loaded ${v.tools.length} tools from MCP servers`)}catch(v){ge(`[MCP] Failed to initialize MCP tools: ${v}`)}let i=e.disableBaseContext??!1,a=e.disableToolGuidance??!1,l={},p=new Set,d=e.defaultProvider||e.provider;if(e.providers)for(let[v,_]of Object.entries(e.providers)){let E=v===d,j=await r.createProvider(v,_,void 0,!E);j&&(l[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},_=await r.createProvider(e.provider,v,void 0,!1);_&&(l[e.provider]=_)}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(([_,E])=>(E.name=E.name||_,E));for(let _ of v){if(typeof _.generate!="function"||typeof _.stream!="function"||typeof _.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let E=_.name;if(!E)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(l[E])throw new Error(`Custom provider name "${E}" conflicts with a built-in provider designation. Choose a different name.`);p.add(E),l[E]=_}}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 yn;if(e.customModes)for(let v of e.customModes)m.register(v);let u={...e.hitl||{}};e.confirmationMode!==void 0&&(u.confirmationMode=e.confirmationMode),u.enabled===void 0&&e.onToolConfirm&&(u.enabled=!0),u.confirmationMode===void 0&&e.onToolConfirm&&(u.confirmationMode="all");let b=new Pn({providers:l,defaultProvider:d,toolRegistry:t,toolsConfig:t.getConfig(),disableBaseContext:i,disableToolGuidance:a,hitlConfig:Object.keys(u).length>0?u:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow,actor:e.actor}),h=new r(b,d,m),T=e.knowledge,C=T==null?[]:Array.isArray(T)?T:[T];h.knowledgeLayers=C.filter(v=>!!v&&typeof v.toTool=="function"),h.registerRequestTools(h._buildKnowledgeRequestTools()),h.customProviderNames=p,h.mcpToolProject=n,h._interceptors=e.interceptors??[];for(let v of h._interceptors)v.init&&await v.init();let S=e.defaultMode||Rt,w=m.get(S);return w&&(b.setMode(w),w.workflow&&h.workflowExecutor.setConfig(w.workflow)),h}static async createProvider(e,t,o,n=!1){if(e==="vertexai")return new En({projectId:t.projectId,location:t.location,googleAuthOptions:t.googleAuthOptions,thinkingBudget:t.thinkingBudget});if(e==="anthropic-vertex")return new $n({projectId:t.projectId,region:t.region});if(["openai","anthropic","gemini","openrouter"].includes(e)){let s=`TOOLPACK_${e.toUpperCase()}_KEY`,i=t.apiKey||process.env[s]||process.env[`${e.toUpperCase()}_API_KEY`];if(!i){if(n)return null;throw new Error(`No API key found for '${e}'. Set ${s} or pass apiKey in config.`)}switch(e){case"openai":return new bt(i,t.baseUrl);case"anthropic":return new Rn(i,t.baseUrl);case"gemini":return new Dn(i);case"openrouter":return new Nn(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new It({baseUrl:t.baseUrl||Mn(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||Mn(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,l=0,p={steps:[]};s.plan.planningResponse?.usage&&(i+=s.plan.planningResponse.usage.prompt_tokens,a+=s.plan.planningResponse.usage.completion_tokens||0,l+=s.plan.planningResponse.usage.total_tokens,p.planning=s.plan.planningResponse.usage);for(let m of s.plan.steps)if(m.status==="completed"&&m.result?.response?.usage){let u=m.result.response.usage;i+=u.prompt_tokens,a+=u.completion_tokens||0,l+=u.total_tokens,p.steps.push({stepNumber:m.number,description:m.description,usage:u})}let d={prompt_tokens:i,completion_tokens:a,total_tokens:l};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||yt();if(t)try{let o=An(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){I(`[Toolpack] Failed to reload config from ${t}: ${o instanceof Error?o.message:String(o)}`)}}getWorkflowExecutor(){return this.workflowExecutor}async disconnect(){let e=this.getProvider();e&&"disconnect"in e&&await e.disconnect(),this.mcpToolProject&&await bs(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[o,n]of e.entries()){let s=this.customProviderNames.has(o),i=[];try{i=await n.getModels()}catch(a){I(`[Toolpack] Failed to fetch models for provider '${o}': ${a}`)}t.push({name:o,displayName:n.getDisplayName(),type:s?"custom":"built-in",models:i})}return t}async loadToolProject(e){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(()=>(Yw(),Xw))).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(ws),t}getMode(){return this.client.getMode()}getActiveModeName(){let e=this.client.getMode();return e?e.displayName:"Default"}getModes(){return this.modeRegistry.getAll()}cycleMode(){let e=this.client.getMode(),t=e?e.name:"default",o=this.modeRegistry.getNext(t);return this.client.setMode(o),o}registerMode(e){this.modeRegistry.register(e)}forwardEvents(e){e instanceof Cl.EventEmitter&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,o)=>this.emit("workflow:completed",t,o)),e.on("workflow:failed",(t,o)=>this.emit("workflow:failed",t,o))}};c();c();c();var Cs=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 ks=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new Cs(e.maxConversations??500),this.maxMessagesPerConversation=e.maxMessagesPerConversation??500}async append(e){let t=this.lru.get(e.conversationId);t||(t=[],this.lru.set(e.conversationId,t)),!t.some(o=>o.id===e.id)&&(t.push(e),t.sort((o,n)=>o.timestamp.localeCompare(n.timestamp)),t.length>this.maxMessagesPerConversation&&t.splice(0,t.length-this.maxMessagesPerConversation))}async get(e,t={}){let n=(this.lru.get(e)??[]).slice();if(t.scope!==void 0&&(n=n.filter(s=>s.scope===t.scope)),t.sinceTimestamp!==void 0&&(n=n.filter(s=>s.timestamp>=t.sinceTimestamp)),t.participantIds!==void 0&&t.participantIds.length>0){let s=new Set(t.participantIds);n=n.filter(i=>s.has(i.participant.id))}return t.limit!==void 0&&n.length>t.limit&&(n=n.slice(n.length-t.limit)),n}async search(e,t,o={}){let n=this.lru.get(e)??[],s=t.toLowerCase(),i=o.limit??10,a=o.tokenCap??2e3,l=n.filter(m=>m.content.toLowerCase().includes(s)).slice().reverse(),p=[],d=0;for(let m of l){if(p.length>=i)break;let u=Math.ceil(m.content.length/4);if(p.length>0&&d+u>a)break;p.push(m),d+=u}return p}async deleteMessages(e,t){let o=this.lru.get(e);if(!o||t.length===0)return;let n=new Set(t),s=o.filter(i=>!n.has(i.id));this.lru.set(e,s)}clearConversation(e){this.lru.set(e,[])}get conversationCount(){return this.lru.size}};c();var Zw=x(require("better-sqlite3"),1),Tn=x(require("fs"),1),Pr=x(require("path"),1);function XC(){let r=Pr.join(process.cwd(),".toolpack","db","conversation");return Tn.existsSync(r)||Tn.mkdirSync(r,{recursive:!0}),Pr.join(r,"conversation.sqlite")}var Ss=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??XC(),o=Pr.dirname(t);if(Tn.existsSync(o)||Tn.mkdirSync(o,{recursive:!0}),this.db=new Zw.default(t),e.enableWAL!==!1){try{this.db.pragma("journal_mode = WAL")}catch{}try{this.db.pragma("synchronous = NORMAL")}catch{}}this.useFTS=e.useFTS===!0,this.maxMessagesPerConversation=e.maxMessagesPerConversation??500,this.initSchema()}initSchema(){this.db.exec(`
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,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 b=d.map(k=>`${e.conversationId}:${k}`),h=b.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${h})`).run(...b)}}}}}async get(e,t={}){let o=["conversation_id = ?"],n=[e];if(t.scope!==void 0&&(o.push("scope = ?"),n.push(t.scope)),t.sinceTimestamp!==void 0&&(o.push("timestamp >= ?"),n.push(t.sinceTimestamp)),t.participantIds&&t.participantIds.length>0){let p=t.participantIds.map(()=>"?").join(",");o.push(`participant_id IN (${p})`),n.push(...t.participantIds)}let i=`SELECT id, conversation_id, participant_kind, participant_id, participant_display_name, content, timestamp, scope, metadata FROM messages ${o.length?`WHERE ${o.join(" AND ")}`:""} ORDER BY timestamp ASC`,c=this.db.prepare(i).all(n).map(p=>this.rowToMessage(p));return t.limit!==void 0&&c.length>t.limit&&(c=c.slice(c.length-t.limit)),c}async search(e,t,o={}){let n=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
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 l=a-this.maxMessagesPerConversation,d=this.db.prepare("SELECT id FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC LIMIT ?").all(e.conversationId,l).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 b=d.map(C=>`${e.conversationId}:${C}`),h=b.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${h})`).run(...b)}}}}}async get(e,t={}){let o=["conversation_id = ?"],n=[e];if(t.scope!==void 0&&(o.push("scope = ?"),n.push(t.scope)),t.sinceTimestamp!==void 0&&(o.push("timestamp >= ?"),n.push(t.sinceTimestamp)),t.participantIds&&t.participantIds.length>0){let p=t.participantIds.map(()=>"?").join(",");o.push(`participant_id IN (${p})`),n.push(...t.participantIds)}let i=`SELECT id, conversation_id, participant_kind, participant_id, participant_display_name, content, timestamp, scope, metadata FROM messages ${o.length?`WHERE ${o.join(" AND ")}`:""} ORDER BY timestamp ASC`,l=this.db.prepare(i).all(n).map(p=>this.rowToMessage(p));return t.limit!==void 0&&l.length>t.limit&&(l=l.slice(l.length-t.limit)),l}async search(e,t,o={}){let n=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
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(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();var Xw=x(require("os"),1),Pt=x(require("path"),1),bn=x(require("fs"),1),vl=".toolpack",Cl="config",kl="toolpack.config.json";function Yw(){return Xw.homedir()}function Zw(){return Pt.join(Yw(),vl)}function Sl(){return Pt.join(Zw(),Cl)}function Sr(){return Pt.join(Sl(),kl)}function ex(r=process.cwd()){return Pt.join(r,vl)}function _l(r=process.cwd()){return Pt.join(ex(r),Cl)}function _r(r=process.cwd()){return Pt.join(_l(r),kl)}function Pl(){let r=Sl();bn.existsSync(r)||bn.mkdirSync(r,{recursive:!0})}function JC(r=process.cwd()){let e=_l(r);bn.existsSync(e)||bn.mkdirSync(e,{recursive:!0})}l();var de=x(require("fs"),1),Cs=x(require("path"),1);function $l(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]=$l(r[o],e[o]):t[o]=e[o];return t}function Rl(r){if(!de.existsSync(r))return null;try{let e=de.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function VC(r=process.cwd()){let e=Cs.join(r,"toolpack.config.json"),t=Sr(),o=_r(r),n=Rl(e)||{},s=Rl(t)||{},i=Rl(o)||{},a=$l(n,s);return a=$l(a,i),a}function QC(r=process.cwd()){let e=Cs.join(r,"toolpack.config.json"),t=Sr(),o=_r(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 XC(r=process.cwd()){let e=Sr();if(!de.existsSync(e)){Pl();let t=null,o=_r(r);if(de.existsSync(o))t=o;else{let s=Cs.join(r,"toolpack.config.json");if(de.existsSync(s))t=s;else{let i=gt();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 YC=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there","then"]),ks=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=>!YC.has(o))}addDocument(e,t){this.documents.set(e,t);let o=this.tokenize(t);this.documentLengths.set(e,o.length);let n={};for(let s of o)n[s]=(n[s]??0)+1;for(let[s,i]of Object.entries(n))this.termFrequencies.has(s)||this.termFrequencies.set(s,new Map),this.termFrequencies.get(s).set(e,i);this.updateAvgDocLength()}clear(){this.documents.clear(),this.termFrequencies.clear(),this.documentLengths.clear(),this.avgDocLength=0}get size(){return this.documents.size}updateAvgDocLength(){if(this.documentLengths.size===0){this.avgDocLength=0;return}let e=0;this.documentLengths.forEach(t=>{e+=t}),this.avgDocLength=e/this.documentLengths.size}idf(e){let t=this.documents.size,o=this.termFrequencies.get(e)?.size??0;return o===0?0:Math.log((t-o+.5)/(o+.5)+1)}search(e,t=10){let o=this.tokenize(e);if(o.length===0)return[];let n={};this.documents.forEach((i,a)=>{let c=0,p=this.documentLengths.get(a)??0;for(let d of o){let m=this.termFrequencies.get(d);if(!m)continue;let f=m.get(a)??0;if(f===0)continue;let b=this.idf(d),h=f*(this.k1+1),T=f+this.k1*(1-this.b+this.b*(p/this.avgDocLength));c+=b*(h/T)}c>0&&(n[a]=c)});let s=Object.entries(n).map(([i,a])=>({id:i,score:a}));return s.sort((i,a)=>a.score-i.score),s.slice(0,t)}};l();var lt=x(require("path"),1);function tx(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(),ne=E.substring(j+1).trim();if(R==="name"&&(n=ne),R==="title"&&(s=ne),R==="version"&&(i=ne),R==="tags")if(ne){let B=ne.match(/\[([^\]]*)\]/);B&&(a=B[1].split(",").map(Z=>Z.trim().replace(/^["']|["']$/g,"")).filter(Boolean))}else P=!0,a=[]}}n||(n=lt.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 f=r.match(/## Instructions\n\n([\s\S]*?)(?=\n## |$)/),b=f&&f[1]?f[1].trim():"",h=r.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/),T=h&&h[1]?h[1].trim():void 0,k=lt.relative(t,e),C=lt.dirname(k),w=C==="."?void 0:C.split(lt.sep)[0];return{name:n,title:s,version:i,tags:a,category:w,filePath:e,description:p,triggers:m,instructions:b,examples:T||void 0,lastModified:0}}0&&(module.exports={AGENT_MODE,AGENT_PLANNING_PROMPT,AGENT_WORKFLOW,AIClient,AnthropicAdapter,AnthropicVertexAdapter,AuthenticationError,BM25Engine,BM25SearchEngine,BUILT_IN_MODES,CHAT_MODE,CHAT_WORKFLOW,CODING_MODE,CODING_PLANNING_PROMPT,CODING_WORKFLOW,CONFIG_DIR_NAME,CONFIG_FILE_NAME,ConnectionError,ContextWindowConfigError,ContextWindowExceededError,ContextWindowStateManager,ConversationNotFoundError,DEFAULT_MODE_NAME,DEFAULT_TOOLS_CONFIG,DEFAULT_TOOL_SEARCH_CONFIG,DEFAULT_WORKFLOW,DEFAULT_WORKFLOW_CONFIG,FILE_LIMITS,GeminiAdapter,InMemoryConversationStore,InsufficientContextError,InvalidRequestError,McpClient,McpConnectionError,McpTimeoutError,McpToolManager,ModeRegistry,OllamaAdapter,OllamaProvider,OpenAIAdapter,OpenRouterAdapter,PageError,Planner,ProviderAdapter,ProviderError,RateLimitError,RuleLoader,SDKError,SQLiteConversationStore,SummarizationError,TOOLPACK_DIR_NAME,TOOL_SEARCH_NAME,TimeoutError,ToolDiscoveryCache,ToolRegistry,ToolRouter,Toolpack,VertexAIAdapter,WorkflowExecutor,addBypassRule,buildSummarizedHistory,cloudDeployTool,cloudListTool,cloudStatusTool,cloudToolsProject,codingExtractFunctionTool,codingFindReferencesTool,codingFindSymbolTool,codingGetCallHierarchyTool,codingGetDiagnosticsTool,codingGetExportsTool,codingGetImportsTool,codingGetOutlineTool,codingGetSymbolsTool,codingGoToDefinitionTool,codingMultiFileEditTool,codingRefactorRenameTool,codingToolsProject,countTokens,createContextWindowStateManager,createMcpToolProject,createMode,createSkillTools,createSummarizationReport,createSummarySystemMessage,createToolProject,dbCountTool,dbDeleteTool,dbInsertTool,dbQueryTool,dbSchemaTool,dbTablesTool,dbToolsProject,dbUpdateTool,diffApplyTool,diffCreateTool,diffPreviewTool,diffToolsProject,disconnectMcpToolProject,ensureGlobalConfigDir,ensureLocalConfigDir,estimateSummaryTokens,estimateTokenCount,execKillTool,execListProcessesTool,execReadOutputTool,execRunBackgroundTool,execRunBlockingTool,execRunShellTool,execRunTool,execTailOutputTool,execToolsProject,extractConversationKeypoints,fetchUrlAsBase64,fsAppendFileTool,fsBatchReadTool,fsBatchWriteTool,fsCopyTool,fsCreateDirTool,fsDeleteDirTool,fsDeleteFileTool,fsExistsTool,fsGlobTool,fsListDirTool,fsMoveTool,fsReadFileRangeTool,fsReadFileTool,fsReplaceInFileTool,fsSearchTool,fsStatTool,fsToolsProject,fsTreeTool,fsWriteFileTool,generateSummarizationPrompt,generateToolCategoriesPrompt,getContextWindowPercentage,getDefaultSlmModel,getGlobalConfigDir,getGlobalConfigPath,getGlobalToolpackDir,getLocalConfigDir,getLocalConfigPath,getLocalToolpackDir,getMessageStats,getMimeType,getOllamaBaseUrl,getOllamaProviderEntries,getRegisteredSlmModels,getRuntimeConfigStatus,getSafeOutputReserve,getToolSearchSchema,getToolpackConfig,getUserHomeDir,gitAddTool,gitBlameTool,gitBranchCreateTool,gitBranchListTool,gitCheckoutTool,gitCloneTool,gitCommitTool,gitDiffTool,gitLogTool,gitStatusTool,gitToolsProject,githubContentsGetTextTool,githubGraphqlExecuteTool,githubIssuesCommentsCreateTool,githubPrDiffGetTool,githubPrFilesListTool,githubPrReviewCommentsReplyTool,githubPrReviewThreadsListTool,githubPrReviewThreadsResolveTool,githubPrReviewsSubmitTool,githubToolsProject,groupMessagesByRole,handleContextWindowError,httpDeleteTool,httpDownloadTool,httpGetTool,httpPostTool,httpPutTool,httpToolsProject,initializeGlobalConfigIfFirstRun,isContextWindowError,isDataUri,isRegisteredSlm,isToolSearchTool,k8sApplyManifestTool,k8sDeleteResourceTool,k8sDescribeTool,k8sGetConfigMapTool,k8sGetLogsTool,k8sGetNamespacesTool,k8sListDeploymentsTool,k8sListPodsTool,k8sListServicesTool,k8sSwitchContextTool,k8sToolsProject,k8sWaitForDeploymentTool,loadFullConfig,loadRuntimeConfig,loadToolsConfig,mergeSummarizationResults,normalizeImagePart,ollamaRequest,ollamaStream,parseDataUri,parseFileEnvelope,parseSkillFile,parseSummarizationResponse,prepareSummarizationRequest,pruneMessages,readFileAsBase64,reloadToolpackConfig,removeBypassRule,saveToolsConfig,slackAuthTestTool,slackChatPostEphemeralTool,slackChatPostMessageTool,slackConversationsHistoryTool,slackConversationsRepliesTool,slackReactionsAddTool,slackToolsProject,systemCwdTool,systemDiskUsageTool,systemEnvTool,systemInfoTool,systemSetEnvTool,systemToolsProject,toDataUri,toolSearchDefinition,truncateMessage,validateSummarizationResult,webExtractLinksTool,webFeedTool,webFetchTool,webMapTool,webMetadataTool,webScrapeTool,webScreenshotTool,webSearchTool,webSitemapTool,webToolsProject,wouldExceedContextWindow});
617
+ ORDER BY timestamp DESC`).all(e,`%${t}%`);let a=i.map(d=>this.rowToMessage(d)),l=[],p=0;for(let d of a){if(l.length>=n)break;let m=Math.ceil(d.content.length/4);if(l.length>0&&p+m>s)break;l.push(d),p+=m}return l}async deleteMessages(e,t){if(!t||t.length===0)return;let o=t.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${o})`).run(e,...t),this.useFTS){let s=t.map(l=>`${e}:${l}`),i=s.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${i})`).run(...s)}}clearConversation(e){this.useFTS&&this.db.prepare("DELETE FROM messages_fts WHERE doc_key LIKE ?").run(`${e}:%`),this.db.prepare("DELETE FROM messages WHERE conversation_id = ?").run(e)}rowToMessage(e){return{id:e.id,conversationId:e.conversation_id,participant:{kind:e.participant_kind,id:e.participant_id,displayName:e.participant_display_name??void 0},content:e.content,timestamp:e.timestamp,scope:e.scope,metadata:e.metadata?JSON.parse(e.metadata):void 0}}close(){try{this.db.close()}catch{}}};c();var ex=x(require("os"),1),$t=x(require("path"),1),wn=x(require("fs"),1),Sl=".toolpack",_l="config",Pl="toolpack.config.json";function tx(){return ex.homedir()}function ox(){return $t.join(tx(),Sl)}function Rl(){return $t.join(ox(),_l)}function Rr(){return $t.join(Rl(),Pl)}function nx(r=process.cwd()){return $t.join(r,Sl)}function $l(r=process.cwd()){return $t.join(nx(r),_l)}function $r(r=process.cwd()){return $t.join($l(r),Pl)}function El(){let r=Rl();wn.existsSync(r)||wn.mkdirSync(r,{recursive:!0})}function YC(r=process.cwd()){let e=$l(r);wn.existsSync(e)||wn.mkdirSync(e,{recursive:!0})}c();var ue=x(require("fs"),1),_s=x(require("path"),1);function Al(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]=Al(r[o],e[o]):t[o]=e[o];return t}function Dl(r){if(!ue.existsSync(r))return null;try{let e=ue.readFileSync(r,"utf-8");return JSON.parse(e)}catch{return null}}function ZC(r=process.cwd()){let e=_s.join(r,"toolpack.config.json"),t=Rr(),o=$r(r),n=Dl(e)||{},s=Dl(t)||{},i=Dl(o)||{},a=Al(n,s);return a=Al(a,i),a}function ek(r=process.cwd()){let e=_s.join(r,"toolpack.config.json"),t=Rr(),o=$r(r),n=!ue.existsSync(t),s=null,i="default";return ue.existsSync(o)?(s=o,i="local"):ue.existsSync(t)?(s=t,i="global"):ue.existsSync(e)&&(s=e,i="base"),{isFirstRun:n,activeConfigPath:s,configSource:i}}function tk(r=process.cwd()){let e=Rr();if(!ue.existsSync(e)){El();let t=null,o=$r(r);if(ue.existsSync(o))t=o;else{let s=_s.join(r,"toolpack.config.json");if(ue.existsSync(s))t=s;else{let i=yt();i&&ue.existsSync(i)&&(t=i)}}let n={};if(t)try{let s=ue.readFileSync(t,"utf-8");n=JSON.parse(s)}catch{}ue.writeFileSync(e,JSON.stringify(n,null,4),"utf-8")}}c();c();var ok=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there","then"]),Ps=class{documents=new Map;termFrequencies=new Map;documentLengths=new Map;avgDocLength=0;k1;b;constructor(e=1.5,t=.75){this.k1=e,this.b=t}tokenize(e){if(!e)return[];let t=e.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=>!ok.has(o))}addDocument(e,t){this.documents.set(e,t);let o=this.tokenize(t);this.documentLengths.set(e,o.length);let n={};for(let s of o)n[s]=(n[s]??0)+1;for(let[s,i]of Object.entries(n))this.termFrequencies.has(s)||this.termFrequencies.set(s,new Map),this.termFrequencies.get(s).set(e,i);this.updateAvgDocLength()}clear(){this.documents.clear(),this.termFrequencies.clear(),this.documentLengths.clear(),this.avgDocLength=0}get size(){return this.documents.size}updateAvgDocLength(){if(this.documentLengths.size===0){this.avgDocLength=0;return}let e=0;this.documentLengths.forEach(t=>{e+=t}),this.avgDocLength=e/this.documentLengths.size}idf(e){let t=this.documents.size,o=this.termFrequencies.get(e)?.size??0;return o===0?0:Math.log((t-o+.5)/(o+.5)+1)}search(e,t=10){let o=this.tokenize(e);if(o.length===0)return[];let n={};this.documents.forEach((i,a)=>{let l=0,p=this.documentLengths.get(a)??0;for(let d of o){let m=this.termFrequencies.get(d);if(!m)continue;let u=m.get(a)??0;if(u===0)continue;let b=this.idf(d),h=u*(this.k1+1),T=u+this.k1*(1-this.b+this.b*(p/this.avgDocLength));l+=b*(h/T)}l>0&&(n[a]=l)});let s=Object.entries(n).map(([i,a])=>({id:i,score:a}));return s.sort((i,a)=>a.score-i.score),s.slice(0,t)}};c();var pt=x(require("path"),1);function rx(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
+ `),_=!1;for(let E of v){if(_){let H=E.match(/^\s+-\s+(.+?)\s*$/);if(H){a.push(H[1].replace(/^["']|["']$/g,""));continue}_=!1}let j=E.indexOf(":");if(j===-1)continue;let R=E.substring(0,j).trim(),re=E.substring(j+1).trim();if(R==="name"&&(n=re),R==="title"&&(s=re),R==="version"&&(i=re),R==="tags")if(re){let H=re.match(/\[([^\]]*)\]/);H&&(a=H[1].split(",").map(ee=>ee.trim().replace(/^["']|["']$/g,"")).filter(Boolean))}else _=!0,a=[]}}n||(n=pt.basename(e,".skill.md"));let l=r.match(/## Description\n\n([\s\S]*?)(?=\n## |$)/),p=l&&l[1]?l[1].trim():"",d=r.match(/## Triggers\n\n([\s\S]*?)(?=\n## |$)/),m=[];if(d&&d[1]){let v=d[1].split(`
619
+ `).filter(_=>_.startsWith("- "));for(let _ of v){let E=_.match(/^- "(.*)"/);E&&E[1]&&m.push(E[1])}}let u=r.match(/## Instructions\n\n([\s\S]*?)(?=\n## |$)/),b=u&&u[1]?u[1].trim():"",h=r.match(/## Examples\n\n([\s\S]*?)(?=\n## |$)/),T=h&&h[1]?h[1].trim():void 0,C=pt.relative(t,e),S=pt.dirname(C),w=S==="."?void 0:S.split(pt.sep)[0];return{name:n,title:s,version:i,tags:a,category:w,filePath:e,description:p,triggers:m,instructions:b,examples:T||void 0,lastModified:0}}0&&(module.exports={AGENT_MODE,AGENT_PLANNING_PROMPT,AGENT_WORKFLOW,AIClient,AbortedError,AnthropicAdapter,AnthropicVertexAdapter,AuthenticationError,BM25Engine,BM25SearchEngine,BUILT_IN_MODES,CHAT_MODE,CHAT_WORKFLOW,CODING_MODE,CODING_PLANNING_PROMPT,CODING_WORKFLOW,CONFIG_DIR_NAME,CONFIG_FILE_NAME,ConnectionError,ContextWindowConfigError,ContextWindowExceededError,ContextWindowStateManager,ConversationNotFoundError,DEFAULT_MODE_NAME,DEFAULT_TOOLS_CONFIG,DEFAULT_TOOL_SEARCH_CONFIG,DEFAULT_WORKFLOW,DEFAULT_WORKFLOW_CONFIG,FILE_LIMITS,GeminiAdapter,InMemoryConversationStore,InsufficientContextError,InvalidRequestError,McpClient,McpConnectionError,McpTimeoutError,McpToolManager,ModeRegistry,OllamaAdapter,OllamaProvider,OpenAIAdapter,OpenRouterAdapter,PageError,Planner,ProviderAdapter,ProviderError,RateLimitError,RuleLoader,SDKError,SQLiteConversationStore,SummarizationError,TOOLPACK_DIR_NAME,TOOL_SEARCH_NAME,TimeoutError,ToolDiscoveryCache,ToolRegistry,ToolRouter,Toolpack,VertexAIAdapter,WorkflowExecutor,addBypassRule,buildSummarizedHistory,cloudDeployTool,cloudListTool,cloudStatusTool,cloudToolsProject,codingExtractFunctionTool,codingFindReferencesTool,codingFindSymbolTool,codingGetCallHierarchyTool,codingGetDiagnosticsTool,codingGetExportsTool,codingGetImportsTool,codingGetOutlineTool,codingGetSymbolsTool,codingGoToDefinitionTool,codingMultiFileEditTool,codingRefactorRenameTool,codingToolsProject,countTokens,createContextWindowStateManager,createMcpToolProject,createMode,createSkillTools,createSummarizationReport,createSummarySystemMessage,createToolProject,dbCountTool,dbDeleteTool,dbInsertTool,dbQueryTool,dbSchemaTool,dbTablesTool,dbToolsProject,dbUpdateTool,diffApplyTool,diffCreateTool,diffPreviewTool,diffToolsProject,disconnectMcpToolProject,ensureGlobalConfigDir,ensureLocalConfigDir,estimateSummaryTokens,estimateTokenCount,execKillTool,execListProcessesTool,execReadOutputTool,execRunBackgroundTool,execRunBlockingTool,execRunShellTool,execRunTool,execTailOutputTool,execToolsProject,extractConversationKeypoints,fetchUrlAsBase64,fsAppendFileTool,fsBatchReadTool,fsBatchWriteTool,fsCopyTool,fsCreateDirTool,fsDeleteDirTool,fsDeleteFileTool,fsExistsTool,fsGlobTool,fsListDirTool,fsMoveTool,fsReadFileRangeTool,fsReadFileTool,fsReplaceInFileTool,fsSearchTool,fsStatTool,fsToolsProject,fsTreeTool,fsWriteFileTool,generateSummarizationPrompt,generateToolCategoriesPrompt,getContextWindowPercentage,getDefaultSlmModel,getGlobalConfigDir,getGlobalConfigPath,getGlobalToolpackDir,getLocalConfigDir,getLocalConfigPath,getLocalToolpackDir,getMessageStats,getMimeType,getOllamaBaseUrl,getOllamaProviderEntries,getRegisteredSlmModels,getRuntimeConfigStatus,getSafeOutputReserve,getToolSearchSchema,getToolpackConfig,getUserHomeDir,gitAddTool,gitBlameTool,gitBranchCreateTool,gitBranchListTool,gitCheckoutTool,gitCloneTool,gitCommitTool,gitDiffTool,gitLogTool,gitStatusTool,gitToolsProject,githubContentsGetTextTool,githubGraphqlExecuteTool,githubIssuesCommentsCreateTool,githubPrDiffGetTool,githubPrFilesListTool,githubPrReviewCommentsReplyTool,githubPrReviewThreadsListTool,githubPrReviewThreadsResolveTool,githubPrReviewsSubmitTool,githubToolsProject,groupMessagesByRole,handleContextWindowError,httpDeleteTool,httpDownloadTool,httpGetTool,httpPostTool,httpPutTool,httpToolsProject,initializeGlobalConfigIfFirstRun,isContextWindowError,isDataUri,isRegisteredSlm,isToolSearchTool,k8sApplyManifestTool,k8sDeleteResourceTool,k8sDescribeTool,k8sGetConfigMapTool,k8sGetLogsTool,k8sGetNamespacesTool,k8sListDeploymentsTool,k8sListPodsTool,k8sListServicesTool,k8sSwitchContextTool,k8sToolsProject,k8sWaitForDeploymentTool,loadFullConfig,loadRuntimeConfig,loadToolsConfig,mergeSummarizationResults,normalizeImagePart,ollamaRequest,ollamaStream,parseDataUri,parseFileEnvelope,parseSkillFile,parseSummarizationResponse,prepareSummarizationRequest,pruneMessages,raceAbort,readFileAsBase64,reloadToolpackConfig,removeBypassRule,saveToolsConfig,slackAuthTestTool,slackChatPostEphemeralTool,slackChatPostMessageTool,slackConversationsHistoryTool,slackConversationsRepliesTool,slackReactionsAddTool,slackToolsProject,systemCwdTool,systemDiskUsageTool,systemEnvTool,systemInfoTool,systemSetEnvTool,systemToolsProject,toDataUri,toolSearchDefinition,truncateMessage,untilAborted,validateSummarizationResult,webExtractLinksTool,webFeedTool,webFetchTool,webMapTool,webMetadataTool,webScrapeTool,webScreenshotTool,webSearchTool,webSitemapTool,webToolsProject,wouldExceedContextWindow});