toolpack-sdk 1.3.0 → 2.0.0-alpha.1
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/README.md +566 -18
- package/dist/index.cjs +324 -139
- package/dist/index.d.cts +1057 -186
- package/dist/index.d.ts +1057 -186
- package/dist/index.js +326 -141
- package/package.json +6 -2
package/dist/index.js
CHANGED
|
@@ -1,121 +1,193 @@
|
|
|
1
|
-
var
|
|
2
|
-
`;og(_r,r)}function Q(s){nt("error",s)}function E(s){nt("warn",s)}function v(s){nt("info",s)}function y(s){nt("debug",s)}function ye(s){nt("trace",s)}function ng(s){return s.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]")}function D(s,e=200){try{let t=typeof s=="string"?s:JSON.stringify(s),r=ng(t);return r.length<=e?r:`${r.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function V(s,e,t){Ee("debug")&&(y(`[${e}][${s}] Messages (${t.length}):`),t.forEach((r,o)=>{y(`[${e}][${s}] #${o} role=${r?.role} content=${D(r?.content,300)}`)}))}var $r,ro,no,_r,k=g(()=>{"use strict";l();$r={error:0,warn:1,info:2,debug:3,trace:4},ro=!1,no="info",_r=rg(process.cwd(),"toolpack-sdk.log")});var st={};re(st,{fetchUrlAsBase64:()=>vs,getMimeType:()=>xs,isDataUri:()=>Ts,normalizeImagePart:()=>cg,parseDataUri:()=>Ps,readFileAsBase64:()=>Cs,toDataUri:()=>lg});import*as ws from"fs/promises";import*as bs from"path";function xs(s){let e=bs.extname(s).toLowerCase();return ag[e]||"application/octet-stream"}function Ts(s){return s.startsWith("data:")}function Ps(s){let e=s.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function lg(s,e){return`data:${e};base64,${s}`}async function Cs(s){try{return{data:(await ws.readFile(s)).toString("base64"),mimeType:xs(s)}}catch(e){throw new M(`Failed to read image file: ${s}`,e)}}async function vs(s){try{let e=await fetch(s);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let t=await e.arrayBuffer(),r=Buffer.from(t),o=e.headers.get("content-type")||"application/octet-stream";return o=o.split(";")[0].trim(),{data:r.toString("base64"),mimeType:o}}catch(e){throw new F(`Failed to download image from URL: ${s}`,"FETCH_ERROR",500,e)}}async function cg(s){if(s.type==="image_data")return{data:s.image_data.data,mimeType:s.image_data.mimeType};if(s.type==="image_file")return await Cs(s.image_file.path);if(s.type==="image_url"){let e=s.image_url.url;if(Ts(e)){let t=Ps(e);if(!t)throw new M(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await vs(e)}throw new M(`Unknown ImagePart type: ${s.type}`)}var ag,Ue=g(()=>{"use strict";l();ce();ag={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Rs,Es,Ds,Ns,As,Ms=g(()=>{"use strict";l();Rs="fs.read_file",Es="Read File",Ds="Read the contents of a file at the given path. Returns the file content as a string.",Ns="filesystem",As={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});import*as We from"fs";async function wg(s){let e=s.path,t=s.encoding||"utf-8";if(y(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!We.existsSync(e))throw new Error(`File not found: ${e}`);if(We.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return We.readFileSync(e,t)}var ct,Ar=g(()=>{"use strict";l();Ms();k();ct={name:Rs,displayName:Es,description:Ds,parameters:As,category:Ns,execute:wg}});var Os,Is,js,Fs,Ls,qs=g(()=>{"use strict";l();Os="fs.write_file",Is="Write File",js="Write content to a file. Creates parent directories if they do not exist. Overwrites existing files.",Fs="filesystem",Ls={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as Ge from"fs";import*as Us from"path";async function bg(s){let e=s.path,t=s.content,r=s.encoding||"utf-8";if(y(`[fs.write-file] execute path="${e}" encoding=${r} content_len=${t?.length??0}`),!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let o=Us.dirname(e);return Ge.existsSync(o)||Ge.mkdirSync(o,{recursive:!0}),Ge.writeFileSync(e,t,r),`File written successfully: ${e} (${Buffer.byteLength(t,r)} bytes)`}var pt,Mr=g(()=>{"use strict";l();qs();k();pt={name:Os,displayName:Is,description:js,parameters:Ls,category:Fs,execute:bg}});var Ws,Gs,Bs,Js,Hs,zs=g(()=>{"use strict";l();Ws="fs.append_file",Gs="Append File",Bs="Append content to the end of a file. Creates the file if it does not exist.",Js="filesystem",Hs={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as Be from"fs";import*as Ks from"path";async function xg(s){let e=s.path,t=s.content,r=s.encoding||"utf-8";if(!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let o=Ks.dirname(e);return Be.existsSync(o)||Be.mkdirSync(o,{recursive:!0}),Be.appendFileSync(e,t,r),`Content appended to: ${e} (${Buffer.byteLength(t,r)} bytes appended)`}var mt,Or=g(()=>{"use strict";l();zs();mt={name:Ws,displayName:Gs,description:Bs,parameters:Hs,category:Js,execute:xg}});var Qs,Ys,Vs,Xs,Zs,ei=g(()=>{"use strict";l();Qs="fs.delete_file",Ys="Delete File",Vs="Delete a file at the given path. Does not delete directories.",Xs="filesystem",Zs={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as Je from"fs";async function Tg(s){let e=s.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!Je.existsSync(e))throw new Error(`File not found: ${e}`);if(Je.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return Je.unlinkSync(e),`File deleted successfully: ${e}`}var dt,Ir=g(()=>{"use strict";l();ei();k();dt={name:Qs,displayName:Ys,description:Vs,parameters:Zs,category:Xs,execute:Tg}});var ti,oi,ri,ni,si,ii=g(()=>{"use strict";l();ti="fs.exists",oi="Exists",ri="Check if a file or directory exists at the given path. Returns true or false.",ni="filesystem",si={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as ai from"fs";async function Pg(s){let e=s.path;if(!e)throw new Error("path is required");let t=ai.existsSync(e);return JSON.stringify({exists:t,path:e})}var ut,jr=g(()=>{"use strict";l();ii();ut={name:ti,displayName:oi,description:ri,parameters:si,category:ni,execute:Pg}});var li,ci,pi,mi,di,ui=g(()=>{"use strict";l();li="fs.stat",ci="Stat",pi="Get file or directory information including size, type, and modification date.",mi="filesystem",di={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as mo from"fs";async function Cg(s){let e=s.path;if(!e)throw new Error("path is required");if(!mo.existsSync(e))throw new Error(`Path not found: ${e}`);let t=mo.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 ft,Fr=g(()=>{"use strict";l();ui();ft={name:li,displayName:ci,description:pi,parameters:di,category:mi,execute:Cg}});var fi,gi,hi,yi,wi,bi=g(()=>{"use strict";l();fi="fs.list_dir",gi="List Directory",hi="List files and directories at the given path. Optionally recurse into subdirectories.",yi="filesystem",wi={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});import*as Ne from"fs";import*as xi from"path";function Ti(s,e,t,r=""){let o=Ne.readdirSync(s,{withFileTypes:!0});for(let n of o){let a=xi.join(s,n.name),i=r?`${r}/${n.name}`:n.name;if(n.isDirectory())t.push({name:i,type:"directory",size:0}),e&&Ti(a,!0,t,i);else if(n.isFile()){let c=Ne.statSync(a);t.push({name:i,type:"file",size:c.size})}}}async function vg(s){let e=s.path,t=s.recursive===!0;if(!e)throw new Error("path is required");if(!Ne.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ne.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let o=[];return Ti(e,t,o),JSON.stringify(o,null,2)}var gt,Lr=g(()=>{"use strict";l();bi();gt={name:fi,displayName:gi,description:hi,parameters:wi,category:yi,execute:vg}});var Pi,Ci,vi,Si,$i,_i=g(()=>{"use strict";l();Pi="fs.create_dir",Ci="Create Directory",vi="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Si="filesystem",$i={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});import*as He from"fs";async function Sg(s){let e=s.path,t=s.recursive!==!1;if(!e)throw new Error("path is required");if(He.existsSync(e)){if(He.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return He.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var ht,qr=g(()=>{"use strict";l();_i();ht={name:Pi,displayName:Ci,description:vi,parameters:$i,category:Si,execute:Sg}});var ki,Ri,Ei,Di,Ni,Ai=g(()=>{"use strict";l();ki="fs.move",Ri="Move",Ei="Move or rename a file or directory from one path to another.",Di="filesystem",Ni={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as Ae from"fs";import*as Mi from"path";async function $g(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Ae.existsSync(e))throw new Error(`Source not found: ${e}`);let r=Mi.dirname(t);return Ae.existsSync(r)||Ae.mkdirSync(r,{recursive:!0}),Ae.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var yt,Ur=g(()=>{"use strict";l();Ai();yt={name:ki,displayName:Ri,description:Ei,parameters:Ni,category:Di,execute:$g}});var Oi,Ii,ji,Fi,Li,qi=g(()=>{"use strict";l();Oi="fs.copy",Ii="Copy",ji="Copy a file or directory from one path to another. Recursively copies directories.",Fi="filesystem",Li={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as K from"fs";import*as wt from"path";function Ui(s,e){if(K.statSync(s).isDirectory()){K.existsSync(e)||K.mkdirSync(e,{recursive:!0});let r=K.readdirSync(s);for(let o of r)Ui(wt.join(s,o),wt.join(e,o))}else K.copyFileSync(s,e)}async function _g(s){let e=s.path,t=s.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!K.existsSync(e))throw new Error(`Source not found: ${e}`);let r=wt.dirname(t);return K.existsSync(r)||K.mkdirSync(r,{recursive:!0}),Ui(e,t),`Copied ${K.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var bt,Wr=g(()=>{"use strict";l();qi();bt={name:Oi,displayName:Ii,description:ji,parameters:Li,category:Fi,execute:_g}});var Wi,Gi,Bi,Ji,Hi,zi=g(()=>{"use strict";l();Wi="fs.read_file_range",Gi="Read File Range",Bi="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",Ji="filesystem",Hi={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});import*as ze from"fs";async function kg(s){let e=s.path,t=s.start_line,r=s.end_line;if(!e)throw new Error("path is required");if(t==null)throw new Error("start_line is required");if(r==null)throw new Error("end_line is required");if(t<1)throw new Error("start_line must be >= 1");if(r<t)throw new Error("end_line must be >= start_line");if(!ze.existsSync(e))throw new Error(`File not found: ${e}`);if(ze.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let a=ze.readFileSync(e,"utf-8").split(`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
1
|
+
var Sy=Object.defineProperty;var h=(n,e)=>()=>(n&&(e=n(n=0)),e);var re=(n,e)=>{for(var t in e)Sy(n,t,{get:e[t],enumerable:!0})};import ky from"path";import{fileURLToPath as Ry}from"url";var $y,_y,u,c=h(()=>{"use strict";$y=()=>Ry(import.meta.url),_y=()=>ky.dirname($y()),u=_y()});function ux(n){return!n||typeof n!="object"?!1:["CONTEXT_WINDOW_EXCEEDED","INSUFFICIENT_CONTEXT","SUMMARIZATION_ERROR","CONTEXT_WINDOW_CONFIG_ERROR","CONVERSATION_NOT_FOUND"].includes(n.code)}function fx(n,e){return n instanceof rn?{shouldRetry:n.isRetryable(),shouldFallback:!0,action:n.isRetryable()?"prune":"fail",message:n.getSuggestedRecovery()}:n instanceof tn?{shouldRetry:!1,shouldFallback:!0,action:n.strategy==="fail"?"prune":"none",message:`Context window exceeded. Strategy: ${n.strategy}`}:n instanceof on?{shouldRetry:!1,shouldFallback:!0,action:"fail",message:"Insufficient context after recovery attempts"}:{shouldRetry:!1,shouldFallback:!1,action:"none",message:"Unknown context window error"}}var A,Se,ke,j,W,qe,hi,yi,tn,on,rn,bi,wi,ne=h(()=>{"use strict";c();A=class extends Error{constructor(t,o,r,s){super(t);this.code=o;this.statusCode=r;this.cause=s;this.name="SDKError"}code;statusCode;cause},Se=class extends A{constructor(e,t){super(e,"AUTHENTICATION_ERROR",401,t),this.name="AuthenticationError"}},ke=class extends A{constructor(t,o,r){super(t,"RATE_LIMIT_ERROR",429,r);this.retryAfter=o;this.name="RateLimitError"}retryAfter},j=class extends A{constructor(e,t){super(e,"INVALID_REQUEST_ERROR",400,t),this.name="InvalidRequestError"}},W=class extends A{constructor(e,t="PROVIDER_ERROR",o=500,r){super(e,t,o,r),this.name="ProviderError"}},qe=class extends A{constructor(e,t){super(e,"CONNECTION_ERROR",503,t),this.name="ConnectionError"}},hi=class extends A{constructor(t,o,r){super(t,"PAGE_ERROR",502,r);this.pageUrl=o;this.name="PageError"}pageUrl},yi=class extends A{constructor(t,o,r){super(t,"TIMEOUT_ERROR",504,r);this.phase=o;this.name="TimeoutError"}phase},tn=class extends A{constructor(t,o,r,s,i,a){super(t,"CONTEXT_WINDOW_EXCEEDED",400,a);this.conversationId=o;this.currentTokens=r;this.contextWindowLimit=s;this.strategy=i;this.name="ContextWindowExceededError"}conversationId;currentTokens;contextWindowLimit;strategy;getOverageTokens(){return Math.max(0,this.currentTokens-this.contextWindowLimit)}getUsagePercentage(){return Math.round(this.currentTokens/this.contextWindowLimit*100)}getDetailedReport(){return`
|
|
2
|
+
Context Window Exceeded
|
|
3
|
+
=======================
|
|
4
|
+
Conversation ID: ${this.conversationId}
|
|
5
|
+
Current Tokens: ${this.currentTokens}
|
|
6
|
+
Context Window Limit: ${this.contextWindowLimit}
|
|
7
|
+
Overage: ${this.getOverageTokens()} tokens
|
|
8
|
+
Usage: ${this.getUsagePercentage()}%
|
|
9
|
+
Strategy: ${this.strategy}
|
|
10
|
+
|
|
11
|
+
Message: ${this.message}
|
|
12
|
+
`.trim()}},on=class extends A{constructor(t,o,r,s,i,a){super(t,"INSUFFICIENT_CONTEXT",400,a);this.conversationId=o;this.requiredTokens=r;this.availableTokens=s;this.minimumRequiredTokens=i;this.name="InsufficientContextError"}conversationId;requiredTokens;availableTokens;minimumRequiredTokens;getDeficit(){return Math.max(0,this.requiredTokens-this.availableTokens)}isRecoverable(){return this.availableTokens>=this.minimumRequiredTokens*.5}getDetailedReport(){return`
|
|
13
|
+
Insufficient Context
|
|
14
|
+
====================
|
|
15
|
+
Conversation ID: ${this.conversationId}
|
|
16
|
+
Required Tokens: ${this.requiredTokens}
|
|
17
|
+
Available Tokens: ${this.availableTokens}
|
|
18
|
+
Deficit: ${this.getDeficit()} tokens
|
|
19
|
+
Minimum Required: ${this.minimumRequiredTokens}
|
|
20
|
+
Recoverable: ${this.isRecoverable()?"Yes":"No"}
|
|
21
|
+
|
|
22
|
+
Message: ${this.message}
|
|
23
|
+
`.trim()}},rn=class extends A{constructor(t,o,r,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=r;this.failureReason=s;this.summaryAttempt=i;this.name="SummarizationError"}conversationId;messageCount;failureReason;summaryAttempt;isRetryable(){return this.failureReason==="provider_error"||this.failureReason==="insufficient_tokens"}getSuggestedRecovery(){switch(this.failureReason){case"provider_error":return"Retry the summarization request or switch to a different summarizer model";case"invalid_response":return"Review the summarizer prompt or use a different model";case"insufficient_tokens":return"Reduce the number of messages to summarize or increase the summary token budget";case"invalid_quality":return"Adjust summarization parameters or use a more capable model";default:return"Manual intervention required"}}getDetailedReport(){let t=`
|
|
24
|
+
Summarization Error
|
|
25
|
+
===================
|
|
26
|
+
Conversation ID: ${this.conversationId}
|
|
27
|
+
Messages Attempted: ${this.messageCount}
|
|
28
|
+
Failure Reason: ${this.failureReason}
|
|
29
|
+
Retryable: ${this.isRetryable()?"Yes":"No"}
|
|
30
|
+
Recovery Action: ${this.getSuggestedRecovery()}
|
|
31
|
+
|
|
32
|
+
Message: ${this.message}`;return this.summaryAttempt?t+`
|
|
33
|
+
|
|
34
|
+
Partial Summary:
|
|
35
|
+
${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}},bi=class extends A{constructor(t,o,r,s,i){super(t,"CONTEXT_WINDOW_CONFIG_ERROR",400,i);this.configField=o;this.providedValue=r;this.constraint=s;this.name="ContextWindowConfigError"}configField;providedValue;constraint;getDetailedReport(){return`
|
|
36
|
+
Context Window Configuration Error
|
|
37
|
+
===================================
|
|
38
|
+
Field: ${this.configField}
|
|
39
|
+
Provided Value: ${JSON.stringify(this.providedValue)}
|
|
40
|
+
Constraint: ${this.constraint}
|
|
41
|
+
|
|
42
|
+
Message: ${this.message}
|
|
43
|
+
`.trim()}},wi=class extends A{constructor(t,o,r){super(t,"CONVERSATION_NOT_FOUND",404,r);this.conversationId=o;this.name="ConversationNotFoundError"}conversationId}});var qy,Y,vt=h(()=>{"use strict";c();qy={enabled:!1,alwaysLoadedTools:[],alwaysLoadedCategories:[],searchResultLimit:5,cacheDiscoveredTools:!0},Y={enabled:!0,autoExecute:!0,maxToolRounds:5,toolChoicePolicy:"auto",resultMaxChars:2e4,enabledTools:[],enabledToolCategories:[],toolSearch:qy}});import{appendFileSync as Ei,mkdirSync as Wy}from"fs";import{dirname as Uy,isAbsolute as Gy,join as By,resolve as zy}from"path";function _i(n){if(!n)return;let e=n.toLowerCase();if(e in mn)return e;console.warn(`[Toolpack Warning] Invalid log level "${n}". Falling back to "info".`)}function Di(n){if(n?.enabled!==void 0&&(et=n.enabled),n?.filePath&&(de=n.filePath),n?.level&&(Ct=_i(n.level)||"info"),process.env.TOOLPACK_SDK_LOG_ENABLED!==void 0&&(et=process.env.TOOLPACK_SDK_LOG_ENABLED==="true"),process.env.TOOLPACK_SDK_LOG_FILE&&(de=process.env.TOOLPACK_SDK_LOG_FILE,et=!0),process.env.TOOLPACK_SDK_LOG_LEVEL&&(Ct=_i(process.env.TOOLPACK_SDK_LOG_LEVEL)||Ct),process.env.TOOLPACK_SDK_LOG_CONSOLE!==void 0&&(dn=process.env.TOOLPACK_SDK_LOG_CONSOLE==="true"),n?.console!==void 0&&process.env.TOOLPACK_SDK_LOG_CONSOLE===void 0&&(dn=n.console),et)try{de=Gy(de)?de:zy(process.cwd(),de),Wy(Uy(de),{recursive:!0}),Ei(de,`[${new Date().toISOString()}] [INFO] [Logger] initialized level=${Ct} file=${de}
|
|
44
|
+
`)}catch(e){console.warn(`[Toolpack Warning] Failed to initialize log file "${de}": ${e.message}`),et=!1}}function Ue(n){return et?mn[n]<=mn[Ct]:!1}function Pt(n,e){if(!Ue(n))return;let o=`[${new Date().toISOString()}] [${n.toUpperCase()}] ${Mi(e)}`;Ei(de,o+`
|
|
45
|
+
`),dn&&(n==="error"?console.error:n==="warn"?console.warn:console.log)(o)}function ee(n){Pt("error",n)}function M(n){Pt("warn",n)}function C(n){Pt("info",n)}function y(n){Pt("debug",n)}function $e(n){Pt("trace",n)}function Mi(n){return n.replace(/\bsk-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bsk-proj-[A-Za-z0-9_-]{10,}\b/g,"[REDACTED]").replace(/\bAIza[0-9A-Za-z_-]{10,}\b/g,"[REDACTED]").replace(/\bBearer\s+[A-Za-z0-9._-]{10,}\b/g,"Bearer [REDACTED]").replace(/\bghs_[A-Za-z0-9]{10,}\b/g,"ghs_[REDACTED]").replace(/\bghp_[A-Za-z0-9]{10,}\b/g,"ghp_[REDACTED]").replace(/\bghu_[A-Za-z0-9]{10,}\b/g,"ghu_[REDACTED]").replace(/\bghr_[A-Za-z0-9]{10,}\b/g,"ghr_[REDACTED]")}function O(n,e=200){try{let t=typeof n=="string"?n:JSON.stringify(n),o=Mi(t);return o.length<=e?o:`${o.slice(0,e)}\u2026`}catch{return"[Unserializable]"}}function se(n,e,t){Ue("debug")&&(y(`[${e}][${n}] Messages (${t.length}):`),t.forEach((o,r)=>{y(`[${e}][${n}] #${r} role=${o?.role} content=${O(o?.content,300)}`)}))}var mn,et,Ct,de,dn,P=h(()=>{"use strict";c();mn={error:0,warn:1,info:2,debug:3,trace:4},et=!1,Ct="info",de=By(process.cwd(),"toolpack-sdk.log"),dn=!1});var St={};re(St,{fetchUrlAsBase64:()=>zi,getMimeType:()=>Wi,isDataUri:()=>Ui,normalizeImagePart:()=>Vy,parseDataUri:()=>Gi,readFileAsBase64:()=>Bi,toDataUri:()=>Qy});import*as Fi from"fs/promises";import*as qi from"path";function Wi(n){let e=qi.extname(n).toLowerCase();return Jy[e]||"application/octet-stream"}function Ui(n){return n.startsWith("data:")}function Gi(n){let e=n.match(/^data:(.*?);base64,(.+)$/);return e?{mimeType:e[1],data:e[2]}:null}function Qy(n,e){return`data:${e};base64,${n}`}async function Bi(n){try{return{data:(await Fi.readFile(n)).toString("base64"),mimeType:Wi(n)}}catch(e){throw new j(`Failed to read image file: ${n}`,e)}}async function zi(n){try{let e=await fetch(n);if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let t=await e.arrayBuffer(),o=Buffer.from(t),r=e.headers.get("content-type")||"application/octet-stream";return r=r.split(";")[0].trim(),{data:o.toString("base64"),mimeType:r}}catch(e){throw new W(`Failed to download image from URL: ${n}`,"FETCH_ERROR",500,e)}}async function Vy(n){if(n.type==="image_data")return{data:n.image_data.data,mimeType:n.image_data.mimeType};if(n.type==="image_file")return await Bi(n.image_file.path);if(n.type==="image_url"){let e=n.image_url.url;if(Ui(e)){let t=Gi(e);if(!t)throw new j(`Malformed data URI provided in image_url: ${e.substring(0,50)}...`);return t}return await zi(e)}throw new j(`Unknown ImagePart type: ${n.type}`)}var Jy,tt=h(()=>{"use strict";c();ne();Jy={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".heic":"image/heic",".heif":"image/heif"}});var Yi,Zi,ea,ta,oa,ra=h(()=>{"use strict";c();Yi="fs.read_file",Zi="Read File",ea="Read the contents of a file at the given path. Returns the file content as a string.",ta="filesystem",oa={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path"]}});import*as rt from"fs";async function nb(n){let e=n.path,t=n.encoding||"utf-8";if(y(`[fs.read-file] execute path="${e}" encoding=${t}`),!e)throw new Error("path is required");if(!rt.existsSync(e))throw new Error(`File not found: ${e}`);if(rt.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);return rt.readFileSync(e,t)}var _t,wn=h(()=>{"use strict";c();ra();P();_t={name:Yi,displayName:Zi,description:ea,parameters:oa,category:ta,execute:nb}});var na,sa,ia,aa,la,ca=h(()=>{"use strict";c();na="fs.write_file",sa="Write File",ia="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.",aa="filesystem",la={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to write"},content:{type:"string",description:"Content to write to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as nt from"fs";import*as pa from"path";async function sb(n){let e=n.path,t=n.content,o=n.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 r=pa.dirname(e);return nt.existsSync(r)||nt.mkdirSync(r,{recursive:!0}),nt.writeFileSync(e,t,o),`File written successfully: ${e} (${Buffer.byteLength(t,o)} bytes)`}var Et,Tn=h(()=>{"use strict";c();ca();P();Et={name:na,displayName:sa,description:ia,parameters:la,category:aa,execute:sb,confirmation:{level:"high",reason:"This will overwrite the entire file contents.",showArgs:["path"]}}});var ma,da,ua,fa,ga,ha=h(()=>{"use strict";c();ma="fs.append_file",da="Append File",ua="Append content to the end of a file. Creates the file if it does not exist.",fa="filesystem",ga={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to append to"},content:{type:"string",description:"Content to append to the file"},encoding:{type:"string",description:"File encoding (default: utf-8)",default:"utf-8"}},required:["path","content"]}});import*as st from"fs";import*as ya from"path";async function ib(n){let e=n.path,t=n.content,o=n.encoding||"utf-8";if(!e)throw new Error("path is required");if(t==null)throw new Error("content is required");let r=ya.dirname(e);return st.existsSync(r)||st.mkdirSync(r,{recursive:!0}),st.appendFileSync(e,t,o),`Content appended to: ${e} (${Buffer.byteLength(t,o)} bytes appended)`}var Dt,xn=h(()=>{"use strict";c();ha();Dt={name:ma,displayName:da,description:ua,parameters:ga,category:fa,execute:ib,confirmation:{level:"medium",reason:"This will modify the file by appending content.",showArgs:["path"]}}});var ba,wa,Ta,xa,va,Ca=h(()=>{"use strict";c();ba="fs.delete_file",wa="Delete File",Ta="Remove/delete a file from the filesystem. Does not delete directories.",xa="filesystem",va={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to delete"}},required:["path"]}});import*as it from"fs";async function ab(n){let e=n.path;if(y(`[fs.delete-file] execute path="${e}"`),!e)throw new Error("path is required");if(!it.existsSync(e))throw new Error(`File not found: ${e}`);if(it.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}. Use a different tool to remove directories.`);return it.unlinkSync(e),`File deleted successfully: ${e}`}var Mt,vn=h(()=>{"use strict";c();Ca();P();Mt={name:ba,displayName:wa,description:Ta,parameters:va,category:xa,execute:ab,confirmation:{level:"high",reason:"This will permanently delete the file. This action cannot be undone.",showArgs:["path"]}}});var Pa,Sa,ka,Ra,$a,_a=h(()=>{"use strict";c();Pa="fs.exists",Sa="Exists",ka="Check if a file or directory exists at the given path. Returns true or false.",Ra="filesystem",$a={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to check"}},required:["path"]}});import*as Ea from"fs";async function lb(n){let e=n.path;if(!e)throw new Error("path is required");let t=Ea.existsSync(e);return JSON.stringify({exists:t,path:e})}var Nt,Cn=h(()=>{"use strict";c();_a();Nt={name:Pa,displayName:Sa,description:ka,parameters:$a,category:Ra,execute:lb}});var Da,Ma,Na,Aa,Oa,Ia=h(()=>{"use strict";c();Da="fs.stat",Ma="Stat",Na="Get file or directory information including size, type, and modification date.",Aa="filesystem",Oa={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to get info for"}},required:["path"]}});import*as Wo from"fs";async function cb(n){let e=n.path;if(!e)throw new Error("path is required");if(!Wo.existsSync(e))throw new Error(`Path not found: ${e}`);let t=Wo.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 At,Pn=h(()=>{"use strict";c();Ia();At={name:Da,displayName:Ma,description:Na,parameters:Oa,category:Aa,execute:cb}});var La,ja,Fa,qa,Wa,Ua=h(()=>{"use strict";c();La="fs.list_dir",ja="List Directory",Fa="List files and directories at the given path. Optionally recurse into subdirectories.",qa="filesystem",Wa={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to list"},recursive:{type:"boolean",description:"Whether to list recursively (default: false)",default:!1}},required:["path"]}});import*as ze from"fs";import*as Ga from"path";function Ba(n,e,t,o=""){let r=ze.readdirSync(n,{withFileTypes:!0});for(let s of r){let i=Ga.join(n,s.name),a=o?`${o}/${s.name}`:s.name;if(s.isDirectory())t.push({name:a,type:"directory",size:0}),e&&Ba(i,!0,t,a);else if(s.isFile()){let l=ze.statSync(i);t.push({name:a,type:"file",size:l.size})}}}async function pb(n){let e=n.path,t=n.recursive===!0;if(!e)throw new Error("path is required");if(!ze.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!ze.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let r=[];return Ba(e,t,r),JSON.stringify(r,null,2)}var Ot,Sn=h(()=>{"use strict";c();Ua();Ot={name:La,displayName:ja,description:Fa,parameters:Wa,category:qa,execute:pb}});var za,Ha,Ka,Ja,Qa,Va=h(()=>{"use strict";c();za="fs.create_dir",Ha="Create Directory",Ka="Create a directory at the given path. Creates parent directories recursively if they do not exist.",Ja="filesystem",Qa={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path to create"},recursive:{type:"boolean",description:"Create parent directories if they do not exist (default: true)",default:!0}},required:["path"]}});import*as at from"fs";async function mb(n){let e=n.path,t=n.recursive!==!1;if(!e)throw new Error("path is required");if(at.existsSync(e)){if(at.statSync(e).isDirectory())return`Directory already exists: ${e}`;throw new Error(`Path exists but is not a directory: ${e}`)}return at.mkdirSync(e,{recursive:t}),`Directory created: ${e}`}var It,kn=h(()=>{"use strict";c();Va();It={name:za,displayName:Ha,description:Ka,parameters:Qa,category:Ja,execute:mb}});var Xa,Ya,Za,el,tl,ol=h(()=>{"use strict";c();Xa="fs.move",Ya="Move",Za="Move or rename a file or directory from one path to another.",el="filesystem",tl={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as He from"fs";import*as rl from"path";async function db(n){let e=n.path,t=n.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!He.existsSync(e))throw new Error(`Source not found: ${e}`);let o=rl.dirname(t);return He.existsSync(o)||He.mkdirSync(o,{recursive:!0}),He.renameSync(e,t),`Moved: ${e} \u2192 ${t}`}var Lt,Rn=h(()=>{"use strict";c();ol();Lt={name:Xa,displayName:Ya,description:Za,parameters:tl,category:el,execute:db,confirmation:{level:"high",reason:"This will move/rename the file or directory, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var nl,sl,il,al,ll,cl=h(()=>{"use strict";c();nl="fs.copy",sl="Copy",il="Copy a file or directory from one path to another. Recursively copies directories.",al="filesystem",ll={type:"object",properties:{path:{type:"string",description:"Source path (file or directory)"},new_path:{type:"string",description:"Destination path"}},required:["path","new_path"]}});import*as Z from"fs";import*as jt from"path";function pl(n,e){if(Z.statSync(n).isDirectory()){Z.existsSync(e)||Z.mkdirSync(e,{recursive:!0});let o=Z.readdirSync(n);for(let r of o)pl(jt.join(n,r),jt.join(e,r))}else Z.copyFileSync(n,e)}async function ub(n){let e=n.path,t=n.new_path;if(!e)throw new Error("path is required");if(!t)throw new Error("new_path is required");if(!Z.existsSync(e))throw new Error(`Source not found: ${e}`);let o=jt.dirname(t);return Z.existsSync(o)||Z.mkdirSync(o,{recursive:!0}),pl(e,t),`Copied ${Z.statSync(e).isDirectory()?"directory":"file"}: ${e} \u2192 ${t}`}var Ft,$n=h(()=>{"use strict";c();cl();Ft={name:nl,displayName:sl,description:il,parameters:ll,category:al,execute:ub,confirmation:{level:"medium",reason:"This will copy files or directories, potentially overwriting the destination.",showArgs:["path","new_path"]}}});var ml,dl,ul,fl,gl,hl=h(()=>{"use strict";c();ml="fs.read_file_range",dl="Read File Range",ul="Read a specific range of lines from a file. Useful for reading portions of large files without loading the entire content.",fl="filesystem",gl={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path to read"},start_line:{type:"integer",description:"Start line number (1-indexed)"},end_line:{type:"integer",description:"End line number (1-indexed, inclusive)"}},required:["path","start_line","end_line"]}});import*as lt from"fs";async function fb(n){let e=n.path,t=n.start_line,o=n.end_line;if(!e)throw new Error("path is required");if(t==null)throw new Error("start_line is required");if(o==null)throw new Error("end_line is required");if(t<1)throw new Error("start_line must be >= 1");if(o<t)throw new Error("end_line must be >= start_line");if(!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}`);let i=lt.readFileSync(e,"utf-8").split(`
|
|
46
|
+
`),a=i.length,l=Math.min(t,a),p=Math.min(o,a),d=i.slice(l-1,p).map((g,w)=>`${l+w}: ${g}`).join(`
|
|
47
|
+
`);return`Lines ${l}-${p} of ${a} total:
|
|
48
|
+
${d}`}var qt,_n=h(()=>{"use strict";c();hl();qt={name:ml,displayName:dl,description:ul,parameters:gl,category:fl,execute:fb}});var yl,bl,wl,Tl,xl,vl=h(()=>{"use strict";c();yl="fs.search",bl="Search",wl="Search for text in files within a directory. Returns matching lines with file paths and line numbers.",Tl="filesystem",xl={type:"object",properties:{path:{type:"string",description:"Directory path to search in"},query:{type:"string",description:"Text or pattern to search for"},recursive:{type:"boolean",description:"Search recursively in subdirectories (default: true)",default:!0},max_results:{type:"integer",description:"Maximum number of matching lines to return (default: 50)",default:50},regex:{type:"boolean",description:"Treat query as a regular expression (default: false)",default:!1},case_sensitive:{type:"boolean",description:"Perform case-sensitive search. If false, search is case-insensitive (default: false)",default:!1}},required:["path","query"]}});import*as Ee from"fs";import*as Cl from"path";function gb(n,e,t,o){try{let s=Ee.readFileSync(n,"utf-8").split(`
|
|
49
|
+
`);for(let i=0;i<s.length&&t.length<o;i++){let a=s[i];(typeof e=="string"?a.includes(e):e.test(a))&&t.push({file:n,line:i+1,content:a.trim()})}}catch{}}function Pl(n,e,t,o,r){let s=Ee.readdirSync(n,{withFileTypes:!0});for(let i of s){if(o.length>=r)break;let a=Cl.join(n,i.name);i.isDirectory()&&t?Pl(a,e,!0,o,r):i.isFile()&&gb(a,e,o,r)}}async function hb(n){let e=n.path,t=n.query,o=n.recursive!==!1,r=n.max_results||50,s=!!n.regex,i=!!n.case_sensitive;if(y(`[fs.search] execute path="${e}" query="${t}" recursive=${o} regex=${s} caseSensitive=${i}`),!e)throw new Error("path is required");if(!t)throw new Error("query is required");let a=t;if(s||!i){let d=t;s||(d=d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));let g=i?"":"i";a=new RegExp(d,g)}if(!Ee.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!Ee.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let p=[];if(Pl(e,a,o,p,r),p.length===0)return`No matches found for "${t}" in ${e}`;let m=p.length>=r?`
|
|
50
|
+
(results capped at ${r})`:"";return JSON.stringify(p,null,2)+m}var Wt,En=h(()=>{"use strict";c();vl();P();Wt={name:yl,displayName:bl,description:wl,parameters:xl,category:Tl,execute:hb}});var Sl,kl,Rl,$l,_l,El=h(()=>{"use strict";c();Sl="fs.replace_in_file",kl="Replace In File",Rl="Find and replace text in a file. Returns the number of replacements made.",$l="filesystem",_l={type:"object",properties:{path:{type:"string",description:"Absolute or relative file path"},search:{type:"string",description:"Text to search for"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}});import*as De from"fs";async function yb(n){let e=n.path,t=n.search,o=n.replace;if(!e)throw new Error("path is required");if(!t)throw new Error("search is required");if(o==null)throw new Error("replace is required");if(!De.existsSync(e))throw new Error(`File not found: ${e}`);if(De.statSync(e).isDirectory())throw new Error(`Path is a directory, not a file: ${e}`);let s=De.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 De.writeFileSync(e,l,"utf-8"),`Replaced ${i} occurrence(s) in ${e}`}var Ut,Dn=h(()=>{"use strict";c();El();Ut={name:Sl,displayName:kl,description:Rl,parameters:_l,category:$l,execute:yb,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 Dl,Ml,Nl,Al,Ol,Il=h(()=>{"use strict";c();Dl="fs.tree",Ml="Tree",Nl="Get a tree representation of a directory structure. Useful for understanding project layout at a glance.",Al="filesystem",Ol={type:"object",properties:{path:{type:"string",description:"Absolute or relative directory path"},depth:{type:"integer",description:"Maximum depth to traverse (default: 3)",default:3}},required:["path"]}});import*as ct from"fs";import*as Uo from"path";function Ll(n,e,t,o,r){if(t>o)return;let i=ct.readdirSync(n,{withFileTypes:!0}).sort((a,l)=>a.isDirectory()&&!l.isDirectory()?-1:!a.isDirectory()&&l.isDirectory()?1:a.name.localeCompare(l.name));for(let a=0;a<i.length;a++){let l=i[a],p=a===i.length-1,m=p?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",d=p?" ":"\u2502 ";l.isDirectory()?(r.push(`${e}${m}${l.name}/`),Ll(Uo.join(n,l.name),e+d,t+1,o,r)):r.push(`${e}${m}${l.name}`)}}async function bb(n){let e=n.path,t=n.depth||3;if(!e)throw new Error("path is required");if(!ct.existsSync(e))throw new Error(`Directory not found: ${e}`);if(!ct.statSync(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);let s=[`${Uo.basename(e)}/`];return Ll(e,"",1,t,s),s.join(`
|
|
51
|
+
`)}var Gt,Mn=h(()=>{"use strict";c();Il();Gt={name:Dl,displayName:Ml,description:Nl,parameters:Ol,category:Al,execute:bb}});var jl,Fl,ql,Wl,Ul,Gl=h(()=>{"use strict";c();jl="fs.glob",Fl="Glob Pattern Match",ql='Find files matching glob patterns (e.g., "**/*.ts", "src/**/*.test.js")',Wl="filesystem",Ul={type:"object",properties:{pattern:{type:"string",description:'Glob pattern to match files (e.g., "**/*.ts", "src/**/*.json")'},cwd:{type:"string",description:"Root directory to search from (defaults to current working directory)"},ignore:{type:"array",items:{type:"string"},description:'Patterns to ignore (e.g., ["node_modules/**", "dist/**"])'},onlyFiles:{type:"boolean",description:"Return only files, not directories (default: true)"},onlyDirectories:{type:"boolean",description:"Return only directories, not files (default: false)"},absolute:{type:"boolean",description:"Return absolute paths instead of relative (default: false)"}},required:["pattern"]}});import wb from"fast-glob";async function Tb(n){let e=n.pattern,t=n.cwd,o=n.ignore,r=n.onlyFiles!==!1,s=n.onlyDirectories===!0,i=n.absolute===!0;if(!e)throw new Error("pattern is required");let a=e.replace(/\\/g,"/");try{let l=await wb(a,{cwd:t||process.cwd(),ignore:o||["node_modules/**",".git/**"],onlyFiles:r,onlyDirectories:s,absolute:i,dot:!0});return JSON.stringify({pattern:e,files:l,count:l.length},null,2)}catch(l){throw new Error(`Failed to glob pattern "${e}": ${l.message}`)}}var Go,Nn=h(()=>{"use strict";c();Gl();Go={name:jl,displayName:Fl,description:ql,parameters:Ul,category:Wl,execute:Tb}});var Bl,zl,Hl,Kl,Jl,Ql=h(()=>{"use strict";c();Bl="fs.delete_dir",zl="Delete Directory",Hl="Delete a directory and all its contents recursively",Kl="filesystem",Jl={type:"object",properties:{path:{type:"string",description:"Absolute or relative path to the directory to delete"},force:{type:"boolean",description:"Force deletion even if directory is not empty (default: true)"}},required:["path"]}});import{rm as xb}from"fs/promises";import{existsSync as vb,statSync as Cb}from"fs";async function Pb(n){let e=n.path,t=n.force!==!1;if(!e)throw new Error("path is required");if(!vb(e))throw new Error(`Directory does not exist: ${e}`);if(!Cb(e).isDirectory())throw new Error(`Path is not a directory: ${e}`);try{return await xb(e,{recursive:!0,force:t}),`Directory deleted successfully: ${e}`}catch(r){throw new Error(`Failed to delete directory "${e}": ${r.message}`)}}var Bo,An=h(()=>{"use strict";c();Ql();Bo={name:Bl,displayName:zl,description:Hl,parameters:Jl,category:Kl,execute:Pb,confirmation:{level:"high",reason:"This will recursively delete the directory and all its contents. This action cannot be undone.",showArgs:["path"]}}});var Vl,Xl,Yl,Zl,ec,tc=h(()=>{"use strict";c();Vl="fs.batch_read",Xl="Batch Read Files",Yl="Read multiple files efficiently in one operation. Returns content for each file or error if read fails.",Zl="filesystem",ec={type:"object",properties:{paths:{type:"array",items:{type:"string"},description:"Array of file paths to read"},encoding:{type:"string",description:"File encoding (default: utf-8)"},continueOnError:{type:"boolean",description:"Continue reading other files if one fails (default: true)"}},required:["paths"]}});import{readFile as Sb}from"fs/promises";async function kb(n){let e=n.paths,t=n.encoding||"utf-8",o=n.continueOnError!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("paths array is required and must not be empty");let r=[],s=0,i=0;for(let a of e)try{let l=await Sb(a,t);r.push({path:a,content:l,success:!0}),s++}catch(l){let p=l.message;if(r.push({path:a,error:p,success:!1}),i++,!o)throw new Error(`Failed to read file "${a}": ${p}`)}return JSON.stringify({total:e.length,success:s,failed:i,results:r},null,2)}var zo,On=h(()=>{"use strict";c();tc();zo={name:Vl,displayName:Xl,description:Yl,parameters:ec,category:Zl,execute:kb}});var oc,rc,nc,sc,ic,ac=h(()=>{"use strict";c();oc="fs.batch_write",rc="Batch Write Files",nc="Write multiple files atomically in one operation. If atomic mode is enabled, all writes succeed or all are rolled back on failure.",sc="filesystem",ic={type:"object",properties:{files:{type:"array",items:{type:"object",properties:{path:{type:"string"},content:{type:"string"}}},description:"Array of files to write, each with path and content"},encoding:{type:"string",description:"File encoding (default: utf-8)"},atomic:{type:"boolean",description:"Atomic mode: rollback all writes if any fails (default: true)"},createDirs:{type:"boolean",description:"Create parent directories if they don't exist (default: true)"}},required:["files"]}});import{writeFile as lc,mkdir as Rb,readFile as $b,unlink as _b}from"fs/promises";import{dirname as Eb,resolve as Db}from"path";import{existsSync as cc}from"fs";async function Mb(n){let e=n.files,t=n.encoding||"utf-8",o=n.atomic!==!1,r=n.createDirs!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("files array is required and must not be empty");for(let a of e)if(!a.path||a.content===void 0)throw new Error("Each file must have path and content properties");let s=[],i=[];try{for(let a of e){let l=Db(a.path);if(o){let p=cc(l),m={path:l,existed:p};p&&(m.originalContent=await $b(l,t)),s.push(m)}if(r){let p=Eb(l);await Rb(p,{recursive:!0})}await lc(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 lc(l.path,l.originalContent,t):!l.existed&&cc(l.path)&&await _b(l.path)}catch{}throw new Error(`Batch write failed and rolled back: ${a.message}`)}throw new Error(`Batch write failed: ${a.message}`)}}var Ho,In=h(()=>{"use strict";c();ac();Ho={name:oc,displayName:rc,description:nc,parameters:ic,category:sc,execute:Mb,confirmation:{level:"high",reason:"This will overwrite multiple files at once.",showArgs:["files"]}}});var mc={};re(mc,{fsAppendFileTool:()=>Dt,fsBatchReadTool:()=>zo,fsBatchWriteTool:()=>Ho,fsCopyTool:()=>Ft,fsCreateDirTool:()=>It,fsDeleteDirTool:()=>Bo,fsDeleteFileTool:()=>Mt,fsExistsTool:()=>Nt,fsGlobTool:()=>Go,fsListDirTool:()=>Ot,fsMoveTool:()=>Lt,fsReadFileRangeTool:()=>qt,fsReadFileTool:()=>_t,fsReplaceInFileTool:()=>Ut,fsSearchTool:()=>Wt,fsStatTool:()=>At,fsToolsProject:()=>pc,fsTreeTool:()=>Gt,fsWriteFileTool:()=>Et});var pc,Ln=h(()=>{"use strict";c();wn();Tn();xn();vn();Cn();Pn();Sn();kn();Rn();$n();_n();En();Dn();Mn();Nn();An();On();In();wn();Tn();xn();vn();Cn();Pn();Sn();kn();Rn();$n();_n();En();Dn();Mn();Nn();An();On();In();pc={manifest:{key:"fs",name:"fs-tools",displayName:"File System",version:"1.0.0",description:"File system tools for reading, writing, searching, and managing files and directories.",author:"Sajeer",tools:["fs.read_file","fs.write_file","fs.append_file","fs.delete_file","fs.exists","fs.stat","fs.list_dir","fs.create_dir","fs.move","fs.copy","fs.read_file_range","fs.search","fs.replace_in_file","fs.tree","fs.glob","fs.delete_dir","fs.batch_read","fs.batch_write"],category:"filesystem"},tools:[_t,Et,Dt,Mt,Nt,At,Ot,It,Lt,Ft,qt,Wt,Ut,Gt,Go,Bo,zo,Ho],dependencies:{"fast-glob":"^3.3.2"}}});var dc,uc,fc,gc,hc,yc=h(()=>{"use strict";c();dc="exec.run",uc="Run",fc="Execute a command directly (without shell) and return its output. Use exec.run_shell for pipes, redirects, or shell features.",gc="execution",hc={type:"object",properties:{command:{type:"string",description:"The command to execute"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});import{execSync as Nb}from"child_process";async function Ab(n){let e=n.command,t=n.cwd,o=n.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 Nb(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"]})||"(command completed with no output)"}catch(r){let s=r.stdout||"",i=r.stderr||"";return`Command failed (exit code ${r.status??"unknown"}):
|
|
9
52
|
STDOUT:
|
|
10
|
-
${
|
|
53
|
+
${s}
|
|
11
54
|
STDERR:
|
|
12
|
-
${
|
|
55
|
+
${i}`}}var Bt,jn=h(()=>{"use strict";c();yc();P();Bt={name:dc,displayName:uc,description:fc,parameters:hc,category:gc,execute:Ab,confirmation:{level:"high",reason:"This will execute a shell command on the host system.",showArgs:["command"]}}});var bc,wc,Tc,xc,vc,Cc=h(()=>{"use strict";c();bc="exec.run_shell",wc="Run Shell",Tc="Execute a command through the system shell. Supports pipes, redirects, environment variable expansion, and other shell features.",xc="execution",vc={type:"object",properties:{command:{type:"string",description:"The shell command to execute (supports pipes, redirects, etc.)"},cwd:{type:"string",description:"Working directory for the command (optional)"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["command"]}});import{execSync as Ob}from"child_process";function Ib(){return process.platform==="win32"?"powershell.exe":process.env.SHELL||"/bin/sh"}async function Lb(n){let e=n.command,t=n.cwd,o=n.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 Ob(e,{cwd:t,timeout:o,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],shell:Ib()})||"(command completed with no output)"}catch(r){let s=r.stdout||"",i=r.stderr||"";return`Command failed (exit code ${r.status??"unknown"}):
|
|
13
56
|
STDOUT:
|
|
14
|
-
${
|
|
57
|
+
${s}
|
|
15
58
|
STDERR:
|
|
16
|
-
${
|
|
17
|
-
`);if(
|
|
18
|
-
${
|
|
19
|
-
|
|
20
|
-
... (truncated, total ${
|
|
21
|
-
${
|
|
22
|
-
${
|
|
23
|
-
${
|
|
24
|
-
|
|
25
|
-
... (truncated, total ${
|
|
26
|
-
${
|
|
27
|
-
${
|
|
28
|
-
|
|
29
|
-
... (truncated)`:`${
|
|
30
|
-
${
|
|
31
|
-
${
|
|
32
|
-
|
|
33
|
-
... (truncated)`:`${
|
|
34
|
-
${
|
|
59
|
+
${i}`}}var zt,Fn=h(()=>{"use strict";c();Cc();P();zt={name:bc,displayName:wc,description:Tc,parameters:vc,category:xc,execute:Lb,confirmation:{level:"high",reason:"This will execute a shell command with explicit shell context.",showArgs:["command"]}}});function Pc(n,e,t){let o=`proc_${jb++}`,r={id:o,command:n,cwd:e,process:t,startedAt:new Date().toISOString(),stdout:"",stderr:""};return t.stdout?.on("data",s=>{r.stdout+=s.toString(),r.stdout.length>1e6&&(r.stdout=r.stdout.slice(-5e5))}),t.stderr?.on("data",s=>{r.stderr+=s.toString(),r.stderr.length>1e6&&(r.stderr=r.stderr.slice(-5e5))}),t.on("exit",()=>{}),Ko.set(o,r),o}function Jo(n){return Ko.get(n)}function Sc(n){let e=Ko.get(n);if(!e)return!1;let t=e.process.exitCode===null;return t&&e.process.kill("SIGTERM"),t}function kc(){return Array.from(Ko.values()).map(n=>({id:n.id,command:n.command,cwd:n.cwd,startedAt:n.startedAt,alive:n.process.exitCode===null,pid:n.process.pid}))}var Ko,jb,Ht=h(()=>{"use strict";c();Ko=new Map,jb=1});var Rc,$c,_c,Ec,Dc,Mc=h(()=>{"use strict";c();Rc="exec.run_background",$c="Run Background",_c="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.",Ec="execution",Dc={type:"object",properties:{command:{type:"string",description:"The command to run in the background"},cwd:{type:"string",description:"Working directory for the command (optional)"}},required:["command"]}});import{spawn as Fb}from"child_process";async function qb(n){let e=n.command,t=n.cwd;if(!e)throw new Error("command is required");if(y(`[exec.run-background] execute command="${e.substring(0,100)}" cwd=${t??"default"}`),!e)throw new Error("command is required");let o=Fb(e,[],{cwd:t,shell:!0,stdio:["ignore","pipe","pipe"],detached:!1}),r=Pc(e,t,o);return JSON.stringify({id:r,pid:o.pid,command:e,message:`Background process started. Use exec.read_output("${r}") to read output, exec.kill("${r}") to stop.`})}var Kt,qn=h(()=>{"use strict";c();Ht();Mc();P();Kt={name:Rc,displayName:$c,description:_c,parameters:Dc,category:Ec,execute:qb,confirmation:{level:"high",reason:"This will spawn a background process that runs unsupervised.",showArgs:["command"]}}});var Nc,Ac,Oc,Ic,Lc,jc=h(()=>{"use strict";c();Nc="exec.read_output",Ac="Read Output",Oc="Read stdout and stderr from a background process started with exec.run_background.",Ic="execution",Lc={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Wb(n){let e=n.process_id;if(!e)throw new Error("process_id is required");let t=Jo(e);if(!t)throw new Error(`Process not found: ${e}`);let o=t.process.exitCode===null;return JSON.stringify({id:t.id,alive:o,exitCode:t.process.exitCode,stdout:t.stdout,stderr:t.stderr})}var Jt,Wn=h(()=>{"use strict";c();Ht();jc();Jt={name:Nc,displayName:Ac,description:Oc,parameters:Lc,category:Ic,execute:Wb}});var Fc,qc,Wc,Uc,Gc,Bc=h(()=>{"use strict";c();Fc="exec.kill",qc="Kill",Wc="Kill a background process started with exec.run_background.",Uc="execution",Gc={type:"object",properties:{process_id:{type:"string",description:"The process ID returned by exec.run_background"}},required:["process_id"]}});async function Ub(n){let e=n.process_id;if(!e)throw new Error("process_id is required");let t=Jo(e);if(!t)throw new Error(`Process not found: ${e}`);return Sc(e)?`Process ${e} (${t.command}) killed successfully.`:`Process ${e} (${t.command}) was already terminated (exit code: ${t.process.exitCode}).`}var Qt,Un=h(()=>{"use strict";c();Ht();Bc();Qt={name:Fc,displayName:qc,description:Wc,parameters:Gc,category:Uc,execute:Ub,confirmation:{level:"medium",reason:"This will terminate a running process.",showArgs:["process_id"]}}});var zc,Hc,Kc,Jc,Qc,Vc=h(()=>{"use strict";c();zc="exec.list_processes",Hc="List Processes",Kc="List all managed background processes started with exec.run_background, including their status.",Jc="execution",Qc={type:"object",properties:{}}});async function Gb(n){let e=kc();return e.length===0?"No managed background processes.":JSON.stringify(e,null,2)}var Vt,Gn=h(()=>{"use strict";c();Ht();Vc();Vt={name:zc,displayName:Hc,description:Kc,parameters:Qc,category:Jc,execute:Gb}});var Yc={};re(Yc,{execKillTool:()=>Qt,execListProcessesTool:()=>Vt,execReadOutputTool:()=>Jt,execRunBackgroundTool:()=>Kt,execRunShellTool:()=>zt,execRunTool:()=>Bt,execToolsProject:()=>Xc});var Xc,Bn=h(()=>{"use strict";c();jn();Fn();qn();Wn();Un();Gn();jn();Fn();qn();Wn();Un();Gn();Xc={manifest:{key:"exec",name:"exec-tools",displayName:"Execution",version:"1.0.0",description:"Code execution tools for running commands, managing background processes, and automation.",author:"Sajeer",tools:["exec.run","exec.run_shell","exec.run_background","exec.read_output","exec.kill","exec.list_processes"],category:"execution"},tools:[Bt,zt,Kt,Jt,Qt,Vt],dependencies:{}}});var Zc,ep,tp,op,rp,np=h(()=>{"use strict";c();Zc="system.info",ep="Info",tp="Get system information including OS, CPU, memory, and architecture.",op="system",rp={type:"object",properties:{}}});import*as I from"os";async function Bb(n){return y("[system.info] execute"),JSON.stringify({platform:I.platform(),arch:I.arch(),release:I.release(),hostname:I.hostname(),uptime:I.uptime(),cpus:{model:I.cpus()[0]?.model||"unknown",count:I.cpus().length},memory:{total:I.totalmem(),free:I.freemem(),used:I.totalmem()-I.freemem()},homedir:I.homedir(),tmpdir:I.tmpdir(),nodeVersion:process.version},null,2)}var Xt,zn=h(()=>{"use strict";c();np();P();Xt={name:Zc,displayName:ep,description:tp,parameters:rp,category:op,execute:Bb}});var sp,ip,ap,lp,cp,pp=h(()=>{"use strict";c();sp="system.env",ip="Environment",ap="Get environment variable(s). If key is provided, returns that specific variable. Otherwise returns all environment variables.",lp="system",cp={type:"object",properties:{key:{type:"string",description:"Specific environment variable name to get (optional, returns all if omitted)"}}}});async function zb(n){let e=n.key;if(y(`[system.env] execute key=${e??"all"}`),e){let r=process.env[e];return r===void 0?`Environment variable "${e}" is not set.`:JSON.stringify({[e]:r})}let t={},o=Object.keys(process.env).sort();for(let r of o)process.env[r]!==void 0&&(t[r]=process.env[r]);return JSON.stringify(t,null,2)}var Yt,Hn=h(()=>{"use strict";c();pp();P();Yt={name:sp,displayName:ip,description:ap,parameters:cp,category:lp,execute:zb}});var mp,dp,up,fp,gp,hp=h(()=>{"use strict";c();mp="system.set_env",dp="Set Environment",up="Set an environment variable for the current session. Does not persist across restarts.",fp="system",gp={type:"object",properties:{key:{type:"string",description:"Environment variable name"},value:{type:"string",description:"Value to set"}},required:["key","value"]}});async function Hb(n){let e=n.key,t=n.value;if(!e)throw new Error("key is required");if(t==null)throw new Error("value is required");let o=process.env[e];return process.env[e]=t,o!==void 0?`Environment variable "${e}" updated (was: "${o}", now: "${t}")`:`Environment variable "${e}" set to "${t}"`}var Zt,Kn=h(()=>{"use strict";c();hp();Zt={name:mp,displayName:dp,description:up,parameters:gp,category:fp,execute:Hb,confirmation:{level:"medium",reason:"This will modify the process environment, affecting all subsequent operations.",showArgs:["key","value"]}}});var yp,bp,wp,Tp,xp,vp=h(()=>{"use strict";c();yp="system.cwd",bp="Current Directory",wp="Get the current working directory of the process.",Tp="system",xp={type:"object",properties:{}}});async function Kb(n){return y("[system.cwd] execute"),JSON.stringify({cwd:process.cwd()})}var eo,Jn=h(()=>{"use strict";c();vp();P();eo={name:yp,displayName:bp,description:wp,parameters:xp,category:Tp,execute:Kb}});var Cp,Pp,Sp,kp,Rp,$p=h(()=>{"use strict";c();Cp="system.disk_usage",Pp="Disk Usage",Sp="Get disk usage information for a given path or the root filesystem.",kp="system",Rp={type:"object",properties:{path:{type:"string",description:"Path to check disk usage for (default: /)",default:"/"}}}});import*as Ep from"fs";import*as Dp from"os";import*as Qo from"path";import{execSync as _p}from"child_process";function Qn(n){let e=["B","KB","MB","GB","TB","PB"],t=n,o=0;for(;t>=1024&&o<e.length-1;)t/=1024,o++;return`${t.toFixed(1)}${e[o]}`}async function Jb(n){let t=n.path||(process.platform==="win32"?Dp.tmpdir():"/");t=Qo.resolve(t);let o=process.platform==="win32";try{let r=Ep.statfsSync(t),s=BigInt(r.blocks)*BigInt(r.bsize),i=BigInt(r.bavail)*BigInt(r.bsize),a=BigInt(r.bfree)*BigInt(r.bsize),l=s-a,p=s>0?Number(l*BigInt(100)/s):0;return JSON.stringify({path:t,filesystem:"statfs",size:Qn(Number(s)),used:Qn(Number(l)),available:Qn(Number(i)),usePercent:`${p}%`,mountedOn:t},null,2)}catch(r){try{if(o){let l=Qo.parse(t).root.replace(/\\$/,"")||"C:",p=`Get-PSDrive -Name ${l.replace(":","")} | Select-Object @{n='Drive';e={$_.Name+':'}},@{n='Used';e={$_.Used}},@{n='Free';e={$_.Free}},@{n='Total';e={$_.Used+$_.Free}} | ConvertTo-Json`,m=_p(p,{encoding:"utf-8",timeout:5e3,shell:"powershell.exe"}),d=JSON.parse(m.trim()),g=d.Total||0,w=d.Free||0,b=d.Used||0,T=g>0?Math.round(b/g*100):0;return JSON.stringify({path:t,filesystem:d.Name||"NTFS",size:`${(g/1024**3).toFixed(1)}G`,used:`${(b/1024**3).toFixed(1)}G`,available:`${(w/1024**3).toFixed(1)}G`,usePercent:`${T}%`,mountedOn:d.Drive||`${l}`},null,2)}let s=_p(`df -h "${t}"`,{encoding:"utf-8",timeout:5e3}),i=s.trim().split(`
|
|
60
|
+
`);if(i.length<2)return s;let a=i[1].split(/\s+/);return JSON.stringify({path:t,filesystem:a[0]||"unknown",size:a[1]||"unknown",used:a[2]||"unknown",available:a[3]||"unknown",usePercent:a[4]||"unknown",mountedOn:a[5]||"unknown"},null,2)}catch(s){throw new Error(`Failed to get disk usage for ${t}: ${r?.message||r}; fallback error: ${s.message}`)}}}var to,Vn=h(()=>{"use strict";c();$p();to={name:Cp,displayName:Pp,description:Sp,parameters:Rp,category:kp,execute:Jb}});var Np={};re(Np,{systemCwdTool:()=>eo,systemDiskUsageTool:()=>to,systemEnvTool:()=>Yt,systemInfoTool:()=>Xt,systemSetEnvTool:()=>Zt,systemToolsProject:()=>Mp});var Mp,Xn=h(()=>{"use strict";c();zn();Hn();Kn();Jn();Vn();zn();Hn();Kn();Jn();Vn();Mp={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:[Xt,Yt,Zt,eo,to],dependencies:{}}});var Ap,Op,Ip,Lp,jp,Fp=h(()=>{"use strict";c();Ap="http.get",Op="GET",Ip="Make an HTTP GET request to a URL and return the response body.",Lp="network",jp={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 Qb(n){let e=n.url,t=n.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||{}}),r=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return o.ok?r.length>qp?`${s}
|
|
61
|
+
${r.substring(0,qp)}
|
|
62
|
+
|
|
63
|
+
... (truncated, total ${r.length} characters)`:`${s}
|
|
64
|
+
${r}`:`${s}
|
|
65
|
+
${r}`}var qp,oo,Yn=h(()=>{"use strict";c();Fp();P();qp=1e5;oo={name:Ap,displayName:Op,description:Ip,parameters:jp,category:Lp,execute:Qb}});var Wp,Up,Gp,Bp,zp,Hp=h(()=>{"use strict";c();Wp="http.post",Up="POST",Gp="Make an HTTP POST request to a URL with an optional body and return the response.",Bp="network",zp={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 Vb(n){let e=n.url,t=n.body,o=n.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 r=await fetch(e,{method:"POST",headers:o,body:t||void 0}),s=await r.text(),i=`HTTP ${r.status} ${r.statusText}`;return s.length>Kp?`${i}
|
|
66
|
+
${s.substring(0,Kp)}
|
|
67
|
+
|
|
68
|
+
... (truncated, total ${s.length} characters)`:`${i}
|
|
69
|
+
${s}`}var Kp,ro,Zn=h(()=>{"use strict";c();Hp();P();Kp=1e5;ro={name:Wp,displayName:Up,description:Gp,parameters:zp,category:Bp,execute:Vb,confirmation:{level:"high",reason:"This will send an HTTP POST request with arbitrary payload.",showArgs:["url","body"]}}});var Jp,Qp,Vp,Xp,Yp,Zp=h(()=>{"use strict";c();Jp="http.put",Qp="PUT",Vp="Make an HTTP PUT request to a URL with an optional body and return the response.",Xp="network",Yp={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 Xb(n){let e=n.url,t=n.body,o=n.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 r=await fetch(e,{method:"PUT",headers:o,body:t||void 0}),s=await r.text(),i=`HTTP ${r.status} ${r.statusText}`;return s.length>em?`${i}
|
|
70
|
+
${s.substring(0,em)}
|
|
71
|
+
|
|
72
|
+
... (truncated)`:`${i}
|
|
73
|
+
${s}`}var em,no,es=h(()=>{"use strict";c();Zp();P();em=1e5;no={name:Jp,displayName:Qp,description:Vp,parameters:Yp,category:Xp,execute:Xb,confirmation:{level:"high",reason:"This will send an HTTP PUT request to overwrite remote resources.",showArgs:["url","body"]}}});var tm,om,rm,nm,sm,im=h(()=>{"use strict";c();tm="http.delete",om="DELETE",rm="Make an HTTP DELETE request to a URL and return the response.",nm="network",sm={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 Yb(n){let e=n.url,t=n.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||{}}),r=await o.text(),s=`HTTP ${o.status} ${o.statusText}`;return r.length>am?`${s}
|
|
74
|
+
${r.substring(0,am)}
|
|
75
|
+
|
|
76
|
+
... (truncated)`:`${s}
|
|
77
|
+
${r}`}var am,so,ts=h(()=>{"use strict";c();im();P();am=1e5;so={name:tm,displayName:om,description:rm,parameters:sm,category:nm,execute:Yb,confirmation:{level:"high",reason:"This will send an HTTP DELETE request to destroy remote resources.",showArgs:["url"]}}});var lm,cm,pm,mm,dm,um=h(()=>{"use strict";c();lm="http.download",cm="Download",pm="Download a file from a URL and save it to a local path.",mm="network",dm={type:"object",properties:{url:{type:"string",description:"The URL to download from"},path:{type:"string",description:"Local file path to save the downloaded file"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"}},required:["url","path"]}});import*as pt from"fs";import*as fm from"path";async function Zb(n){let e=n.url,t=n.path,o=n.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 r=await fetch(e,{method:"GET",headers:o||{}});if(!r.ok)throw new Error(`Download failed: HTTP ${r.status} ${r.statusText}`);let s=Buffer.from(await r.arrayBuffer()),i=fm.dirname(t);return pt.existsSync(i)||pt.mkdirSync(i,{recursive:!0}),pt.writeFileSync(t,s),`Downloaded ${e} \u2192 ${t} (${s.length} bytes)`}var io,os=h(()=>{"use strict";c();um();P();io={name:lm,displayName:cm,description:pm,parameters:dm,category:mm,execute:Zb}});var hm={};re(hm,{httpDeleteTool:()=>so,httpDownloadTool:()=>io,httpGetTool:()=>oo,httpPostTool:()=>ro,httpPutTool:()=>no,httpToolsProject:()=>gm});var gm,rs=h(()=>{"use strict";c();Yn();Zn();es();ts();os();Yn();Zn();es();ts();os();gm={manifest:{key:"http",name:"http-tools",displayName:"HTTP",version:"1.0.0",description:"HTTP tools for making GET, POST, PUT, DELETE requests and downloading files.",author:"Sajeer",tools:["http.get","http.post","http.put","http.delete","http.download"],category:"network"},tools:[oo,ro,no,so,io],dependencies:{}}});var ym,bm,wm,Tm,xm,vm=h(()=>{"use strict";c();ym="github.graphql.execute",bm="GitHub GraphQL",wm=["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(" "),Tm="github",xm={type:"object",properties:{query:{type:"string",description:"GraphQL query string"},variables:{type:"object",description:"Optional GraphQL variables"},repo:{type:"string",description:"owner/name \u2014 used for token resolution when no explicit token is provided"},token:{type:"string",description:"GitHub token (App installation or PAT). Optional \u2014 omit to auto-resolve from server credentials."}},required:["query"]}});function G(n,e){let t={Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28",...e||{}};return n&&(t.Authorization=`Bearer ${n}`),t}var he=h(()=>{"use strict";c()});import*as Sm from"crypto";async function B(n,e){if(e)return e;let t=process.env.GITHUB_PAT;if(t)return t;let o=process.env.GITHUB_APP_ID,r=process.env.GITHUB_APP_PRIVATE_KEY?.replace(/\\n/g,`
|
|
78
|
+
`);if(!o||!r)throw new Error("No GitHub token available. Set GITHUB_PAT, or GITHUB_APP_ID + GITHUB_APP_PRIVATE_KEY.");let s=await ew(o,r,n);return tw(o,r,s)}async function ew(n,e,t){if(!t)throw new Error("Cannot resolve GitHub App installation token without a repo name. Pass args.repo or set GITHUB_PAT.");let o=Pm.get(t);if(o!==void 0)return o;let r=km(n,e),s=await fetch(`https://api.github.com/repos/${t}/installation`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}});if(!s.ok){let a=await s.text();throw new Error(`Failed to look up installation for ${t} (${s.status}): ${a}`)}let i=await s.json();return Pm.set(t,i.id),i.id}async function tw(n,e,t){let o=Cm.get(t);if(o&&o.expiresAt>Date.now()+6e4)return o.token;let r=km(n,e),s=await fetch(`https://api.github.com/app/installations/${t}/access_tokens`,{method:"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}});if(!s.ok){let a=await s.text();throw new Error(`Failed to mint installation token (${s.status}): ${a}`)}let i=await s.json();return Cm.set(t,{token:i.token,expiresAt:new Date(i.expires_at).getTime()}),i.token}function km(n,e){let t=Math.floor(Date.now()/1e3),o={alg:"RS256",typ:"JWT"},r={iat:t-30,exp:t+540,iss:n},s=l=>Buffer.from(JSON.stringify(l)).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_"),i=`${s(o)}.${s(r)}`,a=Sm.createSign("RSA-SHA256");return a.update(i),a.end(),`${i}.`+a.sign(e).toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}var Cm,Pm,ye=h(()=>{"use strict";c();Cm=new Map,Pm=new Map});async function ow(n){let e=n.query,t=n.variables??{},o=await B(n.repo,n.token);y(`[github.graphql.execute] query_len=${e?.length??0}`);let r=await fetch("https://api.github.com/graphql",{method:"POST",headers:G(o,{"Content-Type":"application/json"}),body:JSON.stringify({query:e,variables:t})}),s=await r.text();try{let i=JSON.parse(s);i&&Array.isArray(i.errors)&&i.errors.length>0&&y(`[github.graphql.execute] errors=${i.errors.length}`)}catch{}return`HTTP ${r.status} ${r.statusText}
|
|
79
|
+
${s}`}var ao,ns=h(()=>{"use strict";c();vm();P();he();ye();ao={name:ym,displayName:bm,description:wm,parameters:xm,category:Tm,execute:ow}});var Rm,$m,_m,Em,Dm,Mm=h(()=>{"use strict";c();Rm="github.contents.getText",$m="Get Repo File (Text)",_m="Fetch file content (decoded text) via the GitHub Contents API.",Em="github",Dm={type:"object",properties:{repo:{type:"string",description:"owner/name (e.g. octo/repo)"},path:{type:"string",description:"File path within the repo"},ref:{type:"string",description:"Branch, tag, or commit sha"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of decoded text to return; if exceeded, result is truncated with a footer."}},required:["repo","path"]}});import{Buffer as Vo}from"buffer";async function rw(n){let e=n.repo,t=n.path,o=n.ref,r=await B(e,n.token),s=n.maxBytes?Number(n.maxBytes):void 0,i=t.split("/").map(m=>encodeURIComponent(m)).join("/"),a=`https://api.github.com/repos/${e}/contents/${i}${o?`?ref=${encodeURIComponent(o)}`:""}`;y(`[github.contents.getText] repo=${e} path=${t} ref=${o??""}`);let l=await fetch(a,{method:"GET",headers:G(r)}),p=await l.text();if(!l.ok)return`HTTP ${l.status} ${l.statusText}
|
|
80
|
+
${p}`;try{let d=JSON.parse(p)?.content;if(typeof d=="string"){let g=Vo.from(d.replace(/\n/g,""),"base64").toString("utf8");if(s&&Vo.byteLength(g,"utf8")>s){let w=Vo.from(g,"utf8").subarray(0,s).toString("utf8"),b=`
|
|
81
|
+
\u2026 [truncated, ${s} of ${Vo.byteLength(g,"utf8")} bytes]`;return`HTTP ${l.status} ${l.statusText}
|
|
82
|
+
${w}${b}`}return`HTTP ${l.status} ${l.statusText}
|
|
83
|
+
${g}`}}catch{}return`HTTP ${l.status} ${l.statusText}
|
|
84
|
+
${p}`}var lo,ss=h(()=>{"use strict";c();Mm();P();he();ye();lo={name:Rm,displayName:$m,description:_m,parameters:Dm,category:Em,execute:rw}});var Nm,Am,Om,Im,Lm,jm=h(()=>{"use strict";c();Nm="github.pr.reviewThreads.list",Am="List PR Review Threads",Om="List PR review threads via GraphQL (optionally unresolved only).",Im="github",Lm={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 nw(n){let[e,t]=String(n.repo).split("/"),o=Number(n.number),r=await B(n.repo,n.token),s=!!n.unresolvedOnly,i=n.first?Number(n.first):100,a=n.after?String(n.after):void 0,l=n.commentsFirst?Number(n.commentsFirst):20,p=!!n.includeMeta;y(`[github.pr.reviewThreads.list] repo=${e}/${t} pr=${o} unresolvedOnly=${s} first=${i} after=${a??""} commentsFirst=${l} includeMeta=${p}`);let d=await fetch("https://api.github.com/graphql",{method:"POST",headers:G(r,{"Content-Type":"application/json"}),body:JSON.stringify({query:`query($owner:String!,$name:String!,$number:Int!,$first:Int!,$after:String,$commentsFirst:Int!){
|
|
85
|
+
repository(owner:$owner,name:$name){
|
|
86
|
+
pullRequest(number:$number){
|
|
87
|
+
headRefOid
|
|
88
|
+
reviewThreads(first:$first, after:$after){
|
|
89
|
+
pageInfo{ hasNextPage endCursor }
|
|
90
|
+
nodes{ id isResolved isOutdated comments(first:$commentsFirst){ nodes{ databaseId body author{login} path } } }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}`,variables:{owner:e,name:t,number:o,first:i,after:a,commentsFirst:l}})}),g=await d.text();if(!d.ok)return`HTTP ${d.status} ${d.statusText}
|
|
95
|
+
${g}`;try{let w=JSON.parse(g);w&&Array.isArray(w.errors)&&w.errors.length>0&&y(`[github.pr.reviewThreads.list] errors=${w.errors.length}`);let b=w?.data?.repository?.pullRequest,T=b?.reviewThreads?.pageInfo??{hasNextPage:!1,endCursor:null},x=b?.reviewThreads?.nodes??[];if(s&&(x=x.filter(S=>S?.isResolved===!1)),p){let S={headRefOid:b?.headRefOid,threads:x,pageInfo:T};return`HTTP 200 OK
|
|
96
|
+
${JSON.stringify(S)}`}return`HTTP 200 OK
|
|
97
|
+
${JSON.stringify(x)}`}catch{return`HTTP ${d.status} ${d.statusText}
|
|
98
|
+
${g}`}}var co,is=h(()=>{"use strict";c();jm();he();P();ye();co={name:Nm,displayName:Am,description:Om,parameters:Lm,category:Im,execute:nw}});var Fm,qm,Wm,Um,Gm,Bm=h(()=>{"use strict";c();Fm="github.pr.reviewThreads.resolve",qm="Resolve Review Thread",Wm=["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(" "),Um="github",Gm={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 sw(n){let e=String(n.threadId),t=await B(n.repo,n.token);y(`[github.pr.reviewThreads.resolve] threadId=${e}`);let r=await fetch("https://api.github.com/graphql",{method:"POST",headers:G(t,{"Content-Type":"application/json"}),body:JSON.stringify({query:"mutation($id:ID!){ resolveReviewThread(input:{threadId:$id}) { thread { id isResolved } } }",variables:{id:e}})}),s=await r.text();if(r.ok)try{if(JSON.parse(s).errors?.find(l=>l.type==="FORBIDDEN"))return["TOOL_UNSUPPORTED_FOR_TOKEN_TYPE: resolveReviewThread is not available for GitHub App installation tokens (ghs_*).","GitHub requires a user identity (PAT with repo scope) for this operation.","Fallback action: post a reply on the thread acknowledging the fix and ask the author to resolve it manually."].join(" ")}catch{}return`HTTP ${r.status} ${r.statusText}
|
|
99
|
+
${s}`}var po,as=h(()=>{"use strict";c();Bm();he();P();ye();po={name:Fm,displayName:qm,description:Wm,parameters:Gm,category:Um,execute:sw}});var zm,Hm,Km,Jm,Qm,Vm=h(()=>{"use strict";c();zm="github.pr.reviewComments.reply",Hm="Reply to Review Comment",Km="Reply within an existing PR review thread to maintain continuity.",Jm="github",Qm={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 iw(n){let e=String(n.repo),t=Number(n.number),o=Number(n.inReplyTo),r=String(n.body),s=await B(e,n.token),i=`https://api.github.com/repos/${e}/pulls/${t}/comments/${o}/replies`;y(`[github.pr.reviewComments.reply] repo=${e} inReplyTo=${o}`);let a=await fetch(i,{method:"POST",headers:G(s,{"Content-Type":"application/json"}),body:JSON.stringify({body:r})}),l=await a.text();return`HTTP ${a.status} ${a.statusText}
|
|
100
|
+
${l}`}var mo,ls=h(()=>{"use strict";c();Vm();P();he();ye();mo={name:zm,displayName:Hm,description:Km,parameters:Qm,category:Jm,execute:iw}});var Xm,Ym,Zm,ed,td,od=h(()=>{"use strict";c();Xm="github.pr.diff.get",Ym="Get PR Diff",Zm="Fetch the unified diff for a pull request (text/patch).",ed="github",td={type:"object",properties:{repo:{type:"string",description:"owner/name"},number:{type:"integer",description:"PR number"},token:{type:"string",description:"GitHub token (App installation or PAT)"},maxBytes:{type:"integer",description:"Optional max bytes of diff to return; if exceeded, result is truncated with a footer."}},required:["repo","number"]}});import{Buffer as cs}from"buffer";async function aw(n){let e=String(n.repo),t=Number(n.number),o=await B(e,n.token),r=n.maxBytes?Number(n.maxBytes):void 0,s=`https://api.github.com/repos/${e}/pulls/${t}`;y(`[github.pr.diff.get] repo=${e} pr=${t}`);let i=await fetch(s,{method:"GET",headers:G(o,{Accept:"application/vnd.github.v3.diff"})}),a=await i.text();if(r&&cs.byteLength(a,"utf8")>r){let l=cs.from(a,"utf8").subarray(0,r).toString("utf8"),p=`
|
|
101
|
+
\u2026 [truncated, ${r} of ${cs.byteLength(a,"utf8")} bytes]`;return`HTTP ${i.status} ${i.statusText}
|
|
102
|
+
${l}${p}`}return`HTTP ${i.status} ${i.statusText}
|
|
103
|
+
${a}`}var uo,ps=h(()=>{"use strict";c();od();he();P();ye();uo={name:Xm,displayName:Ym,description:Zm,parameters:td,category:ed,execute:aw}});var rd,nd,sd,id,ad,ld=h(()=>{"use strict";c();rd="github.pr.files.list",nd="List PR Files",sd="List files changed in a PR with positions metadata.",id="github",ad={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 lw(n){let e=String(n.repo),t=Number(n.number),o=await B(e,n.token),r=n.perPage?Number(n.perPage):void 0,s=n.page?Number(n.page):void 0,i=new URLSearchParams;r&&i.set("per_page",String(r)),s&&i.set("page",String(s));let a=`https://api.github.com/repos/${e}/pulls/${t}/files${i.toString()?`?${i.toString()}`:""}`;y(`[github.pr.files.list] repo=${e} pr=${t} perPage=${r??""} page=${s??""}`);let l=await fetch(a,{method:"GET",headers:G(o)}),p=await l.text();return`HTTP ${l.status} ${l.statusText}
|
|
104
|
+
${p}`}var fo,ms=h(()=>{"use strict";c();ld();he();P();ye();fo={name:rd,displayName:nd,description:sd,parameters:ad,category:id,execute:lw}});var cd,pd,md,dd,ud,fd=h(()=>{"use strict";c();cd="github.pr.reviews.submit",pd="Submit PR Review",md="Submit a PR review (APPROVE, REQUEST_CHANGES, or COMMENT), optionally with inline comments.",dd="github",ud={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 cw(n){let e=String(n.repo),t=Number(n.number),o=String(n.event),r=n.body?String(n.body):void 0,s=Array.isArray(n.comments)?n.comments:void 0,i=await B(e,n.token),a=`https://api.github.com/repos/${e}/pulls/${t}/reviews`;y(`[github.pr.reviews.submit] repo=${e} pr=${t} event=${o} comments=${s?.length??0}`);let l={event:o};r&&(l.body=r),s&&s.length>0&&(l.comments=s);let p=await fetch(a,{method:"POST",headers:G(i,{"Content-Type":"application/json"}),body:JSON.stringify(l)}),m=await p.text();return`HTTP ${p.status} ${p.statusText}
|
|
105
|
+
${m}`}var go,ds=h(()=>{"use strict";c();fd();he();P();ye();go={name:cd,displayName:pd,description:md,parameters:ud,category:dd,execute:cw}});var gd,hd,yd,bd,wd,Td=h(()=>{"use strict";c();gd="github.issues.comments.create",hd="Create Issue/PR Comment",yd="Create a comment on an issue or pull request (conversation tab).",bd="github",wd={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 pw(n){let e=String(n.repo),t=Number(n.number),o=String(n.body),r=await B(e,n.token),s=`https://api.github.com/repos/${e}/issues/${t}/comments`;y(`[github.issues.comments.create] repo=${e} number=${t}`);let i=await fetch(s,{method:"POST",headers:G(r,{"Content-Type":"application/json"}),body:JSON.stringify({body:o})}),a=await i.text();return`HTTP ${i.status} ${i.statusText}
|
|
106
|
+
${a}`}var Xo,us=h(()=>{"use strict";c();Td();he();P();ye();Xo={name:gd,displayName:hd,description:yd,parameters:wd,category:bd,execute:pw}});var vd={};re(vd,{githubContentsGetTextTool:()=>lo,githubGraphqlExecuteTool:()=>ao,githubIssuesCommentsCreateTool:()=>Xo,githubPrDiffGetTool:()=>uo,githubPrFilesListTool:()=>fo,githubPrReviewCommentsReplyTool:()=>mo,githubPrReviewThreadsListTool:()=>co,githubPrReviewThreadsResolveTool:()=>po,githubPrReviewsSubmitTool:()=>go,githubToolsProject:()=>xd});var xd,fs=h(()=>{"use strict";c();ns();ss();is();as();ls();ps();ms();ds();us();ns();ss();is();as();ls();ps();ms();ds();us();xd={manifest:{key:"github",name:"github-tools",displayName:"GitHub",version:"1.0.0",description:"GitHub GraphQL/REST tools for PR threads, comments, and contents.",author:"Toolpack",tools:["github.graphql.execute","github.contents.getText","github.pr.reviewThreads.list","github.pr.reviewThreads.resolve","github.pr.reviewComments.reply","github.pr.diff.get","github.pr.files.list","github.pr.reviews.submit","github.issues.comments.create"],category:"network"},tools:[ao,lo,co,po,mo,uo,fo,go,Xo],dependencies:{}}});var Cd,Pd,Sd,kd,Rd,$d=h(()=>{"use strict";c();Cd="web.fetch",Pd="Fetch",Sd="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).",kd="network",Rd={type:"object",properties:{url:{type:"string",description:"The URL to fetch"},extractionMode:{type:"string",description:'Content extraction mode: "full" (raw HTML, 15K limit), "structured" (title, excerpt, key points, main content), or "minimal" (title + 500 char snippet). Default: "full"',enum:["full","structured","minimal"],default:"full"},headers:{type:"object",description:"Optional HTTP headers as key-value pairs"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as gs from"cheerio";function _d(n,e){let t=gs.load(n);t("script, style, nav, header, footer, aside, .advertisement, .ad, .sidebar").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||t('meta[property="og:title"]').attr("content")||"Untitled",r=t('meta[name="author"]').attr("content")||t('meta[property="article:author"]').attr("content")||t(".author").first().text().trim()||void 0,s=t('meta[property="article:published_time"]').attr("content")||t("time").first().attr("datetime")||t(".date, .published").first().text().trim()||void 0,i=["article","main",'[role="main"]',".content",".article-content",".post-content","#content"],a="";for(let w of i){let b=t(w).first();if(b.length>0&&(a=b.text().trim(),a.length>200))break}(!a||a.length<200)&&(a=t("body").text().trim()),a=a.replace(/\s+/g," ").trim();let l=[];t("p").each((w,b)=>{let T=t(b).text().trim();T.length>50&&l.length<3&&l.push(T)});let p=l.join(`
|
|
35
107
|
|
|
36
|
-
`)||
|
|
37
|
-
`)}function
|
|
38
|
-
URL: ${
|
|
108
|
+
`)||a.substring(0,500),m=[];t("h2, h3").each((w,b)=>{let T=t(b).text().trim();T&&T.length>5&&T.length<200&&m.length<10&&m.push(T)});let d=a.split(/\s+/).length,g=a.split(/\s+/);return g.length>2e3&&(a=g.slice(0,2e3).join(" ")+"..."),{title:o,url:e,author:r,publishDate:s,excerpt:p.substring(0,1e3),mainContent:a.substring(0,1e4),keyPoints:m,wordCount:d}}function Ed(n,e){let t=gs.load(n);t("script, style, nav, header, footer").remove();let o=t("title").text().trim()||t("h1").first().text().trim()||"Untitled",r=t('meta[name="description"]').attr("content")||t('meta[property="og:description"]').attr("content")||"";return r||t("p").each((s,i)=>{let a=t(i).text().trim();a.length>50&&!r&&(r=a)}),r||(r=t("body").text().trim().replace(/\s+/g," ")),{title:o,url:e,snippet:r.substring(0,500)}}function Dd(n){let e=[];return e.push(`# ${n.title}`),e.push(`URL: ${n.url}`),n.author&&e.push(`Author: ${n.author}`),n.publishDate&&e.push(`Published: ${n.publishDate}`),e.push(`Word Count: ${n.wordCount}`),e.push(""),n.keyPoints.length>0&&(e.push("## Key Points"),n.keyPoints.forEach(t=>{e.push(`- ${t}`)}),e.push("")),e.push("## Excerpt"),e.push(n.excerpt),e.push(""),e.push("## Main Content"),e.push(n.mainContent),e.join(`
|
|
109
|
+
`)}function Md(n){return`# ${n.title}
|
|
110
|
+
URL: ${n.url}
|
|
39
111
|
|
|
40
|
-
${
|
|
41
|
-
${await
|
|
112
|
+
${n.snippet}`}var Nd=h(()=>{"use strict";c()});async function mw(n){let e=n.url,t=n.extractionMode||"full",o=n.headers,r=n.timeout||3e4;if(y(`[web.fetch] execute url="${e}" mode=${t} timeout=${r}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let s=new AbortController,i=setTimeout(()=>s.abort(),r),a;try{a=await fetch(e,{method:"GET",headers:o||{},signal:s.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${r}ms`):p}finally{clearTimeout(i)}if(!a.ok)return`HTTP ${a.status} ${a.statusText}
|
|
113
|
+
${await a.text()}`;let l=await a.text();if(t==="structured"){let p=_d(l,e);return Dd(p)}else if(t==="minimal"){let p=Ed(l,e);return Md(p)}else return l.length>15e3?l.substring(0,15e3)+`
|
|
42
114
|
|
|
43
|
-
[TRUNCATED: showing 15K of ${
|
|
44
|
-
`)||
|
|
115
|
+
[TRUNCATED: showing 15K of ${l.length} total characters]`:l}var ho,hs=h(()=>{"use strict";c();$d();Nd();P();ho={name:Cd,displayName:Pd,description:Sd,parameters:Rd,category:kd,execute:mw}});var Ad,Od,Id,Ld,jd,Fd=h(()=>{"use strict";c();Ad="web.search",Od="Search",Id="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.",Ld="network",jd={type:"object",properties:{query:{type:"string",description:"The search query"},max_results:{type:"integer",description:"Maximum number of results to return (default: 5)",default:5},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4},include_answer:{type:"boolean",description:"Include AI-generated answer summary (works with Tavily and Brave APIs). Default: false",default:!1},freshness:{type:"string",description:'Time range for fresh/recent results: "day" (last 24h), "week" (last 7 days), "month" (last 31 days), "year" (last 365 days). Ensures latest real-time data. Supported by Tavily and Brave APIs; DuckDuckGo returns general results.',enum:["day","week","month","year"]}},required:["query"]}});import*as Me from"fs";import*as Yo from"path";function Zo(n){let e=Wd(n);if(!Me.existsSync(e))return{};try{let t=Me.readFileSync(e,"utf-8");return JSON.parse(t)}catch{return{}}}function yo(n){let e=Zo(n),t=uw(e.tools||e);return y(JSON.stringify(t??{})),t}function dw(n,e){let t=Wd(e),o={};try{Me.existsSync(t)&&(o=JSON.parse(Me.readFileSync(t,"utf-8")))}catch{o={}}o.tools=n,Me.writeFileSync(t,JSON.stringify(o,null,4),"utf-8")}function uw(n){let e=n.additionalConfigurations||{};return e.webSearch||(e.webSearch={}),!e.webSearch.tavilyApiKey&&process.env.TOOLPACK_TAVILY_API_KEY&&(e.webSearch.tavilyApiKey=process.env.TOOLPACK_TAVILY_API_KEY),!e.webSearch.braveApiKey&&process.env.TOOLPACK_BRAVE_API_KEY&&(e.webSearch.braveApiKey=process.env.TOOLPACK_BRAVE_API_KEY),{enabled:n.enabled??Y.enabled,autoExecute:n.autoExecute??Y.autoExecute,maxToolRounds:n.maxToolRounds??Y.maxToolRounds,toolChoicePolicy:n.toolChoicePolicy??Y.toolChoicePolicy,resultMaxChars:n.resultMaxChars??Y.resultMaxChars,intelligentToolDetection:n.intelligentToolDetection,enabledTools:n.enabledTools??Y.enabledTools,enabledToolCategories:n.enabledToolCategories??Y.enabledToolCategories,toolSearch:n.toolSearch??Y.toolSearch,additionalConfigurations:e}}function Wd(n){return n?n.endsWith(".json")?Yo.resolve(n):Yo.resolve(n,qd):Yo.resolve(process.cwd(),qd)}var qd,ys=h(()=>{"use strict";c();vt();P();qd="toolpack.config.json"});import*as Gd from"cheerio";function hw(n,e){y("[web.search] Parsing DuckDuckGo Lite response");let t=Gd.load(n),o=[];return t("a.result-link").each((s,i)=>{if(o.length>=e)return;let a=t(i),l=a.text().trim(),p=a.attr("href"),m=a.siblings(".result-snippet").text().trim();m||(m=a.parent().text().replace(l,"").trim()),l&&p&&o.push({title:l,link:p,snippet:m.slice(0,200)})}),o}function yw(n){if(n)switch(n){case"day":return 1;case"week":return 7;case"month":return 31;case"year":return 365;default:return}}function Ud(n){if(!n)return"";switch(n){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return""}}async function bw(n){let e=n.query,t=n.max_results||5,o=n.include_answer||!1,r=n.freshness;y(`[web.search] execute query="${e}" max_results=${t} includeAnswer=${o} freshness=${r??"none"}`);let s=`Request timed out after ${n.timeout||3e4}ms`,i=()=>{let d=new AbortController,g=setTimeout(()=>d.abort(),n.timeout||3e4);return{signal:d.signal,clear:()=>clearTimeout(g)}};if(!e)throw new Error("query is required");let a=yo();if(y(`[web.search] config=${JSON.stringify(a)}`),a.additionalConfigurations?.webSearch?.tavilyApiKey){y("[web.search] using Tavily API");try{let{signal:d,clear:g}=i(),w=yw(r),b={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({api_key:a.additionalConfigurations.webSearch.tavilyApiKey,query:e,max_results:t,include_answer:o,...w&&{days:w}}),signal:d};y(`[web.search] Tavily request=${JSON.stringify(b)}`);let T=await fetch("https://api.tavily.com/search",b).finally(g);if(T.ok){let x=await T.json();if(x.results&&x.results.length>0){let S=x.results.map(v=>({title:v.title,link:v.url,snippet:v.content}));return o&&x.answer?JSON.stringify({answer:x.answer,results:S},null,2):JSON.stringify(S,null,2)}}else ee(`[web.search] Tavily search failed with status ${T.status}`)}catch(d){ee(`[web.search] Tavily search failed, falling back: ${d}`)}}if(a.additionalConfigurations?.webSearch?.braveApiKey)try{let{signal:d,clear:g}=i();if(o){let w=Ud(r),b=w?`&freshness=${w}`:"",T=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}&summary=1${b}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:d}).finally(g);if(T.ok){let x=await T.json(),S=x.summarizer?.key;if(S&&x.web?.results){let{signal:v,clear:D}=i(),F=await fetch(`https://api.search.brave.com/res/v1/summarizer/search?key=${S}`,{headers:{Accept:"application/json","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:v}).finally(D);if(F.ok){let k=await F.json(),$=x.web.results.slice(0,t).map(E=>({title:E.title,link:E.url,snippet:E.description})),_=k.summary?.map(E=>E.data).join(`
|
|
116
|
+
`)||k.title;return JSON.stringify({answer:_,results:$},null,2)}}if(x.web?.results){let v=x.web.results.slice(0,t).map(D=>({title:D.title,link:D.url,snippet:D.description}));return JSON.stringify(v,null,2)}}}else{let w=Ud(r),b=w?`&freshness=${w}`:"",T=await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(e)}&count=${Math.min(t,20)}${b}`,{headers:{Accept:"application/json","Accept-Encoding":"gzip","X-Subscription-Token":a.additionalConfigurations.webSearch.braveApiKey},signal:d}).finally(g);if(T.ok){let x=await T.json();if(x.web?.results&&x.web.results.length>0){let S=x.web.results.slice(0,t).map(v=>({title:v.title,link:v.url,snippet:v.description}));return JSON.stringify(S,null,2)}}}}catch(d){M(`[web.search] Brave search failed, falling back: ${d}`)}let{signal:l,clear:p}=i(),m;try{m=await fetch(fw,{method:"POST",headers:{"User-Agent":gw,"Content-Type":"application/x-www-form-urlencoded",Origin:"https://lite.duckduckgo.com",Referer:"https://lite.duckduckgo.com/"},body:new URLSearchParams({q:e}).toString(),signal:l})}catch(d){throw d.name==="AbortError"?new Error(s):d}finally{p()}if(m.ok){let d=await m.text(),g=hw(d,t);if(g.length>0)return JSON.stringify(g,null,2)}return JSON.stringify({error:"search_unavailable",message:`Search failed to find results for "${e}" across all providers.`,suggestion:"Please configure a search provider API key (tavilyApiKey or braveApiKey) in toolpack.config.json under tools.additionalConfigurations.webSearch."})}var fw,gw,bo,bs=h(()=>{"use strict";c();Fd();ys();P();fw="https://lite.duckduckgo.com/lite/",gw="Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1";bo={name:Ad,displayName:Od,description:Id,parameters:jd,category:Ld,execute:bw}});var Bd,zd,Hd,Kd,Jd,Qd=h(()=>{"use strict";c();Bd="web.scrape",zd="Scrape",Hd="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.",Kd="network",Jd={type:"object",properties:{url:{type:"string",description:"The URL to scrape"},section:{type:"string",description:'Optional section name to extract (e.g., "talks", "about", "experience"). Finds the heading containing this text and extracts content until the next same-level heading. Use web.map first to discover available sections.'},format:{type:"string",description:'Output format: "text" (clean readable text) or "tables" (extract table data as JSON array). Default: "text"',enum:["text","tables"],default:"text"},selector:{type:"string",description:"Optional CSS selector to target a specific element. Only use if you know the exact selector exists."},max_length:{type:"integer",description:"Maximum characters to return (default: 6000). Keep small (3000-6000) to avoid context limits.",default:6e3},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as Yd from"cheerio";async function xw(n){let e=n.url,t=n.selector,o=n.section,r=n.format||"text",s=n.max_length||6e3,i=n.timeout||3e4;if(y(`[web.scrape] execute url="${e}" format=${r} selector=${t??"none"} section=${o??"none"} timeout=${i}ms`),!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let a=new AbortController,l=setTimeout(()=>a.abort(),i),p;try{p=await fetch(e,{method:"GET",headers:{"User-Agent":ww},signal:a.signal})}catch(b){throw b.name==="AbortError"?new Error(`Request timed out after ${i}ms`):b}finally{clearTimeout(l)}if(!p.ok)throw new Error(`Failed to fetch ${e}: HTTP ${p.status} ${p.statusText}`);let m=await p.text(),d=Yd.load(m);for(let b of Tw)d(b).remove();if(r==="tables"){let b=[];return d("table").each((T,x)=>{let S=[],v=[];d(x).find("th").each((D,F)=>{v.push(d(F).text().trim())}),d(x).find("tr").each((D,F)=>{let k=v.length>0?{}:[],$=d(F).find("td");$.length>0&&($.each((_,E)=>{let U=d(E).text().trim();v.length>0&&v[_]?k[v[_]]=U:k.push(U)}),S.push(k))}),S.length>0&&b.push({id:`Table ${T+1}`,headers:v.length>0?v:void 0,rows:S})}),b.length===0?`No tables found on ${e}`:JSON.stringify(b,null,2)}let g="";if(o){let b=o.toLowerCase(),T=null,x=0;if(d("h1, h2, h3, h4, h5, h6").each((S,v)=>{if(d(v).text().toLowerCase().includes(b))return T=v,x=parseInt(v.tagName.charAt(1)),!1}),T){let S=d(T),v=[],D=S.next();for(;D.length>0;){let F=D.prop("tagName")?.toLowerCase();if(F&&/^h[1-6]$/.test(F)&&parseInt(F.charAt(1))<=x)break;let k=D.text().trim();k&&v.push(k),D=D.next()}v.length>0?(g=v.join(`
|
|
45
117
|
|
|
46
|
-
`).replace(/\s+/g," ").trim(),
|
|
118
|
+
`).replace(/\s+/g," ").trim(),g=`[Section: "${o}"]
|
|
47
119
|
|
|
48
|
-
${
|
|
120
|
+
${g}`):g=`[Note: Found heading "${o}" but no content below it. Falling back to full page.]
|
|
49
121
|
|
|
50
|
-
`}else
|
|
122
|
+
`}else g=`[Note: Section "${o}" not found. Falling back to full page.]
|
|
51
123
|
|
|
52
|
-
`}if(!
|
|
124
|
+
`}if(!g||g.includes("Falling back to full page"))if(g&&g.includes("Falling back to full page")&&(g=""),t){let b=d(t);if(b.length>0)g=b.text().replace(/\s+/g," ").trim();else{for(let T of Vd){let x=d(T);if(x.length>0){let S=x.text().replace(/\s+/g," ").trim();if(S.length>Xd){g=S;break}}}if(g)g=`[Note: Selector "${t}" not found. Showing auto-detected main content instead.]
|
|
53
125
|
|
|
54
|
-
${
|
|
126
|
+
${g}`;else return`No element found matching selector "${t}" and could not auto-detect main content from ${e}`}}else for(let b of Vd){let T=d(b);if(T.length>0){let x=T.text().replace(/\s+/g," ").trim();if(x.length>Xd){g=x;break}}}if(g||(g=d("body").text().replace(/\s+/g," ").trim(),g&&(g=`[Note: Could not detect main content area. Showing full page text (may include navigation).]
|
|
55
127
|
|
|
56
|
-
${
|
|
128
|
+
${g}`)),!g)return`Could not extract any content from ${e}`;if(g.length>s){let b=g.substring(0,s);return`[Warning: Content exceeds ${s} chars (actual: ${g.length} chars). Showing first ${s} chars only.]
|
|
57
129
|
|
|
58
130
|
RECOMMENDATION: Use web.map to see page structure, then use web.scrape with section parameter to extract specific sections.
|
|
59
131
|
|
|
60
132
|
Page content from ${e}:
|
|
61
133
|
|
|
62
|
-
${
|
|
134
|
+
${b}
|
|
63
135
|
|
|
64
|
-
... [Content truncated. ${
|
|
136
|
+
... [Content truncated. ${g.length-s} chars remaining. Use section parameter to extract specific sections.]`}return`Page content from ${e}:
|
|
65
137
|
|
|
66
|
-
${
|
|
138
|
+
${g}`}var ww,Tw,Vd,Xd,wo,ws=h(()=>{"use strict";c();Qd();P();ww="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",Tw=["script","style","nav","footer","header","iframe",".ads",".sidebar","noscript"],Vd=["article","main",".content","#content",'[role="main"]',"body"],Xd=200;wo={name:Bd,displayName:zd,description:Hd,parameters:Jd,category:Kd,execute:xw}});var Zd,eu,tu,ou,ru,nu=h(()=>{"use strict";c();Zd="web.extract_links",eu="Extract Links",tu="Extract all links from a webpage. Returns an array of objects with text and URL. Optionally filter by pattern.",ou="network",ru={type:"object",properties:{url:{type:"string",description:"The URL to extract links from"},filter:{type:"string",description:'Optional filter: "same-domain" to only include links from the same domain, or a substring to match against URLs'},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as su from"cheerio";async function Cw(n){let e=n.url,t=n.filter,o=n.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=new AbortController,s=setTimeout(()=>r.abort(),o),i;try{i=await fetch(e,{method:"GET",headers:{"User-Agent":vw},signal:r.signal})}catch(d){throw d.name==="AbortError"?new Error(`Request timed out after ${o}ms`):d}finally{clearTimeout(s)}if(!i.ok)throw new Error(`Failed to fetch ${e}: HTTP ${i.status} ${i.statusText}`);let a=await i.text(),l=su.load(a),p=new URL(e),m=[];return l("a[href]").each((d,g)=>{let w=l(g),b=w.attr("href");if(!b)return;let T;try{T=new URL(b,e).toString()}catch{return}if(T.startsWith("javascript:")||T.startsWith("mailto:")||T.startsWith("tel:"))return;let x=w.text().trim()||"[no text]";if(t){if(t==="same-domain")try{if(new URL(T).hostname!==p.hostname)return}catch{return}else if(!T.includes(t))return}m.push({text:x,url:T})}),m.length===0?`No links found on ${e}${t?` matching filter "${t}"`:""}`:JSON.stringify(m,null,2)}var vw,To,Ts=h(()=>{"use strict";c();nu();vw="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";To={name:Zd,displayName:eu,description:tu,parameters:ru,category:ou,execute:Cw}});var iu,au,lu,cu,pu,mu=h(()=>{"use strict";c();iu="web.map",au="Map",lu="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.",cu="network",pu={type:"object",properties:{url:{type:"string",description:"The URL to map"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as du from"cheerio";async function Sw(n){let e=n.url,t=n.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=new AbortController,r=setTimeout(()=>o.abort(),t),s;try{s=await fetch(e,{method:"GET",headers:{"User-Agent":Pw},signal:o.signal})}catch(m){throw m.name==="AbortError"?new Error(`Request timed out after ${t}ms`):m}finally{clearTimeout(r)}if(!s.ok)throw new Error(`Failed to fetch ${e}: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a=du.load(i),l=[];if(a("h1, h2, h3, h4, h5, h6").each((m,d)=>{let g=d.tagName.toLowerCase(),w=parseInt(g.charAt(1)),b=a(d).text().trim();b&&l.push({level:w,text:b})}),l.length===0)return`No headings found on ${e}. The page may not have a clear structure.`;let p=`Page outline for ${e}:
|
|
67
139
|
|
|
68
|
-
`;for(let m of
|
|
69
|
-
`}return p}var
|
|
70
|
-
`);for(let m of p){if(c.length>=t)break;let f=m.trim();if(f.toLowerCase().startsWith("sitemap:"))c.push({loc:f.substring(8).trim()});else if(f.toLowerCase().startsWith("allow:")){let h=f.substring(6).trim();c.push({loc:new URL(h,o).toString()})}}}return JSON.stringify(c,null,2)}var Dh,So,kn=g(()=>{"use strict";l();Yp();Dh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";So={name:Jp,displayName:Hp,description:zp,parameters:Qp,category:Kp,execute:Nh}});var Xp,Zp,em,tm,om,rm=g(()=>{"use strict";l();Xp="web.feed",Zp="Extract Feed",em="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",tm="network",om={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 nm(){try{let s=await import("rss-parser");return new(s.default||s)}catch{throw new Error("rss-parser is not installed. Please install it using `npm install rss-parser` to use this feature.")}}var sm=g(()=>{"use strict";l()});async function Ah(s){let e=s.url,t=s.max_entries||10,r=s.timeout||3e4;if(!e)throw new Error("url is required");let o=await nm();o.options={...o.options,timeout:r};try{let n=await o.parseURL(e),a=n.items.slice(0,t).map(i=>({title:i.title,link:i.link,published:i.pubDate||i.isoDate,summary:i.contentSnippet||i.content}));return JSON.stringify({feedTitle:n.title,feedDescription:n.description,entries:a},null,2)}catch(n){throw new Error(`Failed to parse feed from ${e}: ${n.message}`)}}var $o,Rn=g(()=>{"use strict";l();rm();sm();$o={name:Xp,displayName:Zp,description:em,parameters:om,category:tm,execute:Ah}});var im,am,lm,cm,pm,mm=g(()=>{"use strict";l();im="web.screenshot",am="Screenshot",lm="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",cm="network",pm={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 dm(){try{let s=await import("puppeteer");return s.default||s}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var um=g(()=>{"use strict";l()});async function Oh(s){let e=s.url,t=s.format||"html",r=s.viewport,o=s.timeout||3e4;if(!e)throw new Error("url is required");let a=await(await dm()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let i=await a.newPage();if(await i.setUserAgent(Mh),await i.setViewport({width:r?.width||1280,height:r?.height||800}),await i.goto(e,{waitUntil:"networkidle2",timeout:o}),t==="png"){let c=await i.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 i.content()}finally{await a.close()}}var Mh,_o,En=g(()=>{"use strict";l();mm();um();Mh="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";_o={name:im,displayName:am,description:lm,parameters:pm,category:cm,execute:Oh}});var gm={};re(gm,{webExtractLinksTool:()=>Jt,webFeedTool:()=>$o,webFetchTool:()=>Ut,webMapTool:()=>Co,webMetadataTool:()=>vo,webScrapeTool:()=>Bt,webScreenshotTool:()=>_o,webSearchTool:()=>Gt,webSitemapTool:()=>So,webToolsProject:()=>fm});var fm,Dn=g(()=>{"use strict";l();xn();Pn();Cn();vn();Sn();$n();kn();Rn();En();xn();Pn();Cn();vn();Sn();$n();kn();Rn();En();fm={manifest:{key:"web",name:"web-tools",displayName:"Web",version:"1.0.0",description:"Web intelligence tools for fetching, searching, scraping, and extracting content from the web.",author:"Sajeer",tools:["web.fetch","web.search","web.scrape","web.extract_links","web.map","web.metadata","web.sitemap","web.feed","web.screenshot"],category:"network"},tools:[Ut,Gt,Bt,Jt,Co,vo,So,$o,_o],dependencies:{cheerio:"^1.0.0-rc.12"}}});var hm,ym,wm,bm,xm,Tm=g(()=>{"use strict";l();hm="coding.find_symbol",ym="Find Symbol",wm="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",bm="coding",xm={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});import{extname as Ih}from"path";function ko(s){let e=Ih(s).toLowerCase();return jh[e]||"unknown"}var jh,Nn=g(()=>{"use strict";l();jh={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});import*as Me from"web-tree-sitter";import*as pe from"fs";import*as Te from"path";import*as Cm from"os";var Pm,An,Fh,Ro,vm=g(()=>{"use strict";l();Pm=Me.default||Me.Parser||Me,An=Te.join(Cm.homedir(),".toolpack-sdk","grammars"),Fh=Te.resolve(d,"../../grammars"),Ro=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Pm.init({locateFile(e,t){return Te.join(d,"../../../../../../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 r=await this.resolveGrammarPath(e),n=await(Me.Language||Pm.Language).load(r);return this.grammars.set(e,n),n}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,r=Te.resolve(d,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(pe.existsSync(r))return r;let o=Te.join(Fh,t);if(pe.existsSync(o))return o;let n=Te.join(An,t);return pe.existsSync(n)||await this.downloadGrammar(e,n),n}async downloadGrammar(e,t){pe.existsSync(An)||pe.mkdirSync(An,{recursive:!0});let r=`https://unpkg.com/tree-sitter-wasms@latest/out/tree-sitter-${e}.wasm`,o=await fetch(r);if(!o.ok)throw new Error(`Failed to download grammar for ${e}: ${o.statusText}`);let n=await o.arrayBuffer(),a=Buffer.from(n);pe.writeFileSync(t,a)}}});import*as Ht from"web-tree-sitter";import*as Sm from"fs";import*as $m from"crypto";var Lh,Eo,_m=g(()=>{"use strict";l();Nn();vm();Lh=Ht.default||Ht.Parser||Ht,Eo=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new Ro}hash(e){return $m.createHash("md5").update(e).digest("hex")}async getTree(e,t){let r=t!==void 0?t:Sm.readFileSync(e,"utf-8"),o=this.hash(r),n=this.treeCache.get(e),a=ko(e);if(a==="unknown")throw new Error(`Unsupported file type for ${e}`);let i=await this.grammarManager.ensureGrammar(a);if(n&&n.contentHash===o)return n.lastAccessed=Date.now(),{tree:n.tree,language:n.language,grammar:i};this.parser||(await this.grammarManager.init(),this.parser=new Lh),this.parser.setLanguage(i);let c;return n?(n.tree&&n.tree.delete(),c=this.parser.parse(r)):c=this.parser.parse(r),this.treeCache.set(e,{tree:c,language:a,contentHash:o,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:c,language:a,grammar:i}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[r,o]of this.treeCache.entries())o.lastAccessed<t&&(t=o.lastAccessed,e=r);if(e){let r=this.treeCache.get(e);r&&r.tree.delete(),this.treeCache.delete(e)}}}});import{parse as qh}from"@babel/parser";import*as Mn from"@babel/traverse";var se,Do,km=g(()=>{"use strict";l();se=Mn.default||Mn,Do=class{parseCode(e){return qh(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,r){let o=[];try{let n=this.parseCode(e.content),a=e.filePath;se(n,{FunctionDeclaration(i){i.node.id?.name===t&&(!r||r==="function")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(i){i.node.id?.name===t&&(!r||r==="class")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let c=i.parent,p=c.type==="VariableDeclaration"?c.kind:"variable";(!r||r===p||r==="variable")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(i){i.node.id.name===t&&(!r||r==="interface")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(i){i.node.id.name===t&&(!r||r==="type")&&o.push({file:a,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return o}async getSymbols(e,t){let r=[];try{let o=this.parseCode(e.content);se(o,{FunctionDeclaration(n){n.node.id?.name&&(!t||t==="function")&&r.push({name:n.node.id.name,kind:"function",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},ClassDeclaration(n){n.node.id?.name&&(!t||t==="class")&&r.push({name:n.node.id.name,kind:"class",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},VariableDeclarator(n){if(n.node.id.type==="Identifier"){let a=n.parent,i=a.type==="VariableDeclaration"?a.kind:"variable";(!t||t===i||t==="variable")&&r.push({name:n.node.id.name,kind:i,line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}},TSInterfaceDeclaration(n){(!t||t==="interface")&&r.push({name:n.node.id.name,kind:"interface",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})},TSTypeAliasDeclaration(n){(!t||t==="type")&&r.push({name:n.node.id.name,kind:"type",line:n.node.loc?.start.line||0,column:n.node.loc?.start.column||0})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return r}async getImports(e){let t=[];try{let r=this.parseCode(e.content);se(r,{ImportDeclaration(o){let n=o.node.source.value,a=[],i="side-effect";for(let c of o.node.specifiers)if(c.type==="ImportDefaultSpecifier")a.push(c.local.name),i="default";else if(c.type==="ImportNamespaceSpecifier")a.push(`* as ${c.local.name}`),i="namespace";else if(c.type==="ImportSpecifier"){let p=c.imported.type==="Identifier"?c.imported.name:c.imported.value,m=c.local.name;a.push(p===m?p:`${p} as ${m}`),i="named"}t.push({source:n,imports:a,line:o.node.loc?.start.line||0,type:i})}})}catch(r){throw new Error(`Failed to parse file "${e.filePath}": ${r.message}`)}return t}async findReferences(e,t,r){let o=[];try{let n=e.content,a=n.split(`
|
|
71
|
-
`),
|
|
72
|
-
`),
|
|
73
|
-
`),
|
|
74
|
-
function ${
|
|
140
|
+
`;for(let m of l){let d=" ".repeat(m.level-1);p+=`${d}${"#".repeat(m.level)} ${m.text}
|
|
141
|
+
`}return p}var Pw,er,xs=h(()=>{"use strict";c();mu();Pw="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";er={name:iu,displayName:au,description:lu,parameters:pu,category:cu,execute:Sw}});var uu,fu,gu,hu,yu,bu=h(()=>{"use strict";c();uu="web.metadata",fu="Extract Metadata",gu="Extract Open Graph, Twitter Cards, JSON-LD, and meta tags from a URL.",hu="network",yu={type:"object",properties:{url:{type:"string",description:"The URL to extract metadata from"},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as wu from"cheerio";async function Rw(n){let e=n.url,t=n.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let o=new AbortController,r=setTimeout(()=>o.abort(),t),s;try{s=await fetch(e,{method:"GET",headers:{"User-Agent":kw},signal:o.signal})}catch(p){throw p.name==="AbortError"?new Error(`Request timed out after ${t}ms`):p}finally{clearTimeout(r)}if(!s.ok)throw new Error(`Failed to fetch ${e}: HTTP ${s.status} ${s.statusText}`);let i=await s.text(),a=wu.load(i),l={title:a("title").text()||"",description:a('meta[name="description"]').attr("content")||a('meta[property="og:description"]').attr("content")||"",author:a('meta[name="author"]').attr("content")||"",openGraph:{},twitter:{},jsonLd:[]};return a('meta[property^="og:"]').each((p,m)=>{let d=a(m).attr("property")?.replace("og:",""),g=a(m).attr("content");d&&g&&(l.openGraph[d]=g)}),a('meta[name^="twitter:"]').each((p,m)=>{let d=a(m).attr("name")?.replace("twitter:",""),g=a(m).attr("content");d&&g&&(l.twitter[d]=g)}),a('script[type="application/ld+json"]').each((p,m)=>{let d=a(m).html();if(d)try{l.jsonLd.push(JSON.parse(d))}catch{}}),JSON.stringify(l,null,2)}var kw,tr,vs=h(()=>{"use strict";c();bu();kw="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";tr={name:uu,displayName:fu,description:gu,parameters:yu,category:hu,execute:Rw}});var Tu,xu,vu,Cu,Pu,Su=h(()=>{"use strict";c();Tu="web.sitemap",xu="Extract Sitemap",vu="Parse sitemap.xml or robots.txt to discover all pages on a site. Returns an array of URLs with lastmod/priority if available.",Cu="network",Pu={type:"object",properties:{url:{type:"string",description:"The base URL or direct sitemap.xml / robots.txt URL"},max_urls:{type:"integer",description:"Maximum number of URLs to return (default: 100)",default:100},timeout:{type:"integer",description:"Timeout in milliseconds (default: 30000)",default:3e4}},required:["url"]}});import*as ku from"cheerio";async function Cs(n,e){let t=new AbortController,o=setTimeout(()=>t.abort(),e);try{return await fetch(n,{method:"GET",headers:{"User-Agent":$w},signal:t.signal})}catch(r){throw r.name==="AbortError"?new Error(`Request timed out after ${e}ms`):r}finally{clearTimeout(o)}}async function _w(n){let e=n.url,t=n.max_urls||100,o=n.timeout||3e4;if(!e)throw new Error("url is required");if(!e.startsWith("http://")&&!e.startsWith("https://"))throw new Error("url must start with http:// or https://");let r=e,s=!1;!e.endsWith(".xml")&&!e.endsWith(".txt")&&(r=new URL(e.endsWith("/")?"sitemap.xml":"/sitemap.xml",e).toString(),s=!0);let i;try{i=await Cs(r,o),!i.ok&&s&&(r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Cs(r,o))}catch(p){if(s)r=new URL(e.endsWith("/")?"robots.txt":"/robots.txt",e).toString(),i=await Cs(r,o);else throw p}if(!i||!i.ok)throw new Error(`Failed to fetch sitemap or robots.txt from ${e}`);let a=await i.text(),l=[];if(r.endsWith(".xml")||a.trim().startsWith("<")){let p=ku.load(a,{xmlMode:!0}),m=p("sitemap > loc");if(m.length>0)return m.each((g,w)=>{l.length>=t||l.push({loc:p(w).text()})}),JSON.stringify({type:"sitemapindex",urls:l},null,2);p("urlset > url").each((g,w)=>{if(l.length>=t)return;let b=p(w);l.push({loc:b.children("loc").text(),lastmod:b.children("lastmod").text()||void 0,priority:b.children("priority").text()||void 0})})}else{let p=a.split(`
|
|
142
|
+
`);for(let m of p){if(l.length>=t)break;let d=m.trim();if(d.toLowerCase().startsWith("sitemap:"))l.push({loc:d.substring(8).trim()});else if(d.toLowerCase().startsWith("allow:")){let g=d.substring(6).trim();l.push({loc:new URL(g,r).toString()})}}}return JSON.stringify(l,null,2)}var $w,or,Ps=h(()=>{"use strict";c();Su();$w="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";or={name:Tu,displayName:xu,description:vu,parameters:Pu,category:Cu,execute:_w}});var Ru,$u,_u,Eu,Du,Mu=h(()=>{"use strict";c();Ru="web.feed",$u="Extract Feed",_u="Parse RSS/Atom feeds and return structured entries. Requires rss-parser library to be installed.",Eu="network",Du={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 Nu(){try{let n=await import("rss-parser");return new(n.default||n)}catch{throw new Error("rss-parser is not installed. Please install it using `npm install rss-parser` to use this feature.")}}var Au=h(()=>{"use strict";c()});async function Ew(n){let e=n.url,t=n.max_entries||10,o=n.timeout||3e4;if(!e)throw new Error("url is required");let r=await Nu();r.options={...r.options,timeout:o};try{let s=await r.parseURL(e),i=s.items.slice(0,t).map(a=>({title:a.title,link:a.link,published:a.pubDate||a.isoDate,summary:a.contentSnippet||a.content}));return JSON.stringify({feedTitle:s.title,feedDescription:s.description,entries:i},null,2)}catch(s){throw new Error(`Failed to parse feed from ${e}: ${s.message}`)}}var rr,Ss=h(()=>{"use strict";c();Mu();Au();rr={name:Ru,displayName:$u,description:_u,parameters:Du,category:Eu,execute:Ew}});var Ou,Iu,Lu,ju,Fu,qu=h(()=>{"use strict";c();Ou="web.screenshot",Iu="Screenshot",Lu="Render a page with headless browser and return screenshot Base64 PNG or rendered HTML.",ju="network",Fu={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 Wu(){try{let n=await import("puppeteer");return n.default||n}catch{throw new Error("Puppeteer is not installed. Please install it using `npm install puppeteer` to use this feature.")}}var Uu=h(()=>{"use strict";c()});async function Mw(n){let e=n.url,t=n.format||"html",o=n.viewport,r=n.timeout||3e4;if(!e)throw new Error("url is required");let i=await(await Wu()).launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]});try{let a=await i.newPage();if(await a.setUserAgent(Dw),await a.setViewport({width:o?.width||1280,height:o?.height||800}),await a.goto(e,{waitUntil:"networkidle2",timeout:r}),t==="png"){let l=await a.screenshot({type:"png",fullPage:!0}),p;return Buffer.isBuffer(l)?p=l.toString("base64"):p=Buffer.from(l).toString("base64"),`data:image/png;base64,${p}`}else return await a.content()}finally{await i.close()}}var Dw,nr,ks=h(()=>{"use strict";c();qu();Uu();Dw="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36";nr={name:Ou,displayName:Iu,description:Lu,parameters:Fu,category:ju,execute:Mw}});var Bu={};re(Bu,{webExtractLinksTool:()=>To,webFeedTool:()=>rr,webFetchTool:()=>ho,webMapTool:()=>er,webMetadataTool:()=>tr,webScrapeTool:()=>wo,webScreenshotTool:()=>nr,webSearchTool:()=>bo,webSitemapTool:()=>or,webToolsProject:()=>Gu});var Gu,Rs=h(()=>{"use strict";c();hs();bs();ws();Ts();xs();vs();Ps();Ss();ks();hs();bs();ws();Ts();xs();vs();Ps();Ss();ks();Gu={manifest:{key:"web",name:"web-tools",displayName:"Web",version:"1.0.0",description:"Web intelligence tools for fetching, searching, scraping, and extracting content from the web.",author:"Sajeer",tools:["web.fetch","web.search","web.scrape","web.extract_links","web.map","web.metadata","web.sitemap","web.feed","web.screenshot"],category:"network"},tools:[ho,bo,wo,To,er,tr,or,rr,nr],dependencies:{cheerio:"^1.0.0-rc.12"}}});var zu,Hu,Ku,Ju,Qu,Vu=h(()=>{"use strict";c();zu="coding.find_symbol",Hu="Find Symbol",Ku="Find function, class, or variable definitions in JavaScript/TypeScript files using AST parsing",Ju="coding",Qu={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find (function, class, variable, etc.)"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["symbol","path"]}});import{extname as Nw}from"path";function sr(n){let e=Nw(n).toLowerCase();return Aw[e]||"unknown"}var Aw,$s=h(()=>{"use strict";c();Aw={".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".ts":"typescript",".tsx":"tsx",".py":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".hpp":"cpp",".cc":"cpp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".hs":"haskell",".ex":"elixir",".exs":"elixir",".html":"html",".htm":"html",".css":"css",".json":"json",".yaml":"yaml",".yml":"yaml",".md":"markdown",".sh":"bash",".bash":"bash"}});import*as Ke from"web-tree-sitter";import*as xe from"fs";import*as Ne from"path";import*as Yu from"os";var Xu,_s,Ow,ir,Zu=h(()=>{"use strict";c();Xu=Ke.default||Ke.Parser||Ke,_s=Ne.join(Yu.homedir(),".toolpack-sdk","grammars"),Ow=Ne.resolve(u,"../../grammars"),ir=class{grammars=new Map;isInitialized=!1;async init(){this.isInitialized||(await Xu.init({locateFile(e,t){return Ne.join(u,"../../../../../../node_modules/web-tree-sitter",e)}}),this.isInitialized=!0)}async ensureGrammar(e){await this.init();let t=this.grammars.get(e);if(t)return t;let o=await this.resolveGrammarPath(e),s=await(Ke.Language||Xu.Language).load(o);return this.grammars.set(e,s),s}async resolveGrammarPath(e){let t=`tree-sitter-${e}.wasm`,o=Ne.resolve(u,"../../../../../../node_modules/tree-sitter-wasms/out",t);if(xe.existsSync(o))return o;let r=Ne.join(Ow,t);if(xe.existsSync(r))return r;let s=Ne.join(_s,t);return xe.existsSync(s)||await this.downloadGrammar(e,s),s}async downloadGrammar(e,t){xe.existsSync(_s)||xe.mkdirSync(_s,{recursive:!0});let o=`https://unpkg.com/tree-sitter-wasms@latest/out/tree-sitter-${e}.wasm`,r=await fetch(o);if(!r.ok)throw new Error(`Failed to download grammar for ${e}: ${r.statusText}`);let s=await r.arrayBuffer(),i=Buffer.from(s);xe.writeFileSync(t,i)}}});import*as xo from"web-tree-sitter";import*as ef from"fs";import*as tf from"crypto";var Iw,ar,of=h(()=>{"use strict";c();$s();Zu();Iw=xo.default||xo.Parser||xo,ar=class{treeCache=new Map;maxCacheSize=50;parser=null;grammarManager;constructor(){this.grammarManager=new ir}hash(e){return tf.createHash("md5").update(e).digest("hex")}async getTree(e,t){let o=t!==void 0?t:ef.readFileSync(e,"utf-8"),r=this.hash(o),s=this.treeCache.get(e),i=sr(e);if(i==="unknown")throw new Error(`Unsupported file type for ${e}`);let a=await this.grammarManager.ensureGrammar(i);if(s&&s.contentHash===r)return s.lastAccessed=Date.now(),{tree:s.tree,language:s.language,grammar:a};this.parser||(await this.grammarManager.init(),this.parser=new Iw),this.parser.setLanguage(a);let l;return s?(s.tree&&s.tree.delete(),l=this.parser.parse(o)):l=this.parser.parse(o),this.treeCache.set(e,{tree:l,language:i,contentHash:r,lastAccessed:Date.now()}),this.evictIfNeeded(),{tree:l,language:i,grammar:a}}evictIfNeeded(){if(this.treeCache.size<=this.maxCacheSize)return;let e="",t=1/0;for(let[o,r]of this.treeCache.entries())r.lastAccessed<t&&(t=r.lastAccessed,e=o);if(e){let o=this.treeCache.get(e);o&&o.tree.delete(),this.treeCache.delete(e)}}}});import{parse as Lw}from"@babel/parser";import*as Es from"@babel/traverse";var be,lr,rf=h(()=>{"use strict";c();be=Es.default||Es,lr=class{parseCode(e){return Lw(e,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]})}async findSymbols(e,t,o){let r=[];try{let s=this.parseCode(e.content),i=e.filePath;be(s,{FunctionDeclaration(a){a.node.id?.name===t&&(!o||o==="function")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"function",name:t})},ClassDeclaration(a){a.node.id?.name===t&&(!o||o==="class")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"class",name:t})},VariableDeclarator(a){if(a.node.id.type==="Identifier"&&a.node.id.name===t){let l=a.parent,p=l.type==="VariableDeclaration"?l.kind:"variable";(!o||o===p||o==="variable")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:p,name:t})}},TSInterfaceDeclaration(a){a.node.id.name===t&&(!o||o==="interface")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"interface",name:t})},TSTypeAliasDeclaration(a){a.node.id.name===t&&(!o||o==="type")&&r.push({file:i,line:a.node.loc?.start.line||0,column:a.node.loc?.start.column||0,kind:"type",name:t})}})}catch{}return r}async getSymbols(e,t){let o=[];try{let r=this.parseCode(e.content);be(r,{FunctionDeclaration(s){s.node.id?.name&&(!t||t==="function")&&o.push({name:s.node.id.name,kind:"function",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},ClassDeclaration(s){s.node.id?.name&&(!t||t==="class")&&o.push({name:s.node.id.name,kind:"class",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},VariableDeclarator(s){if(s.node.id.type==="Identifier"){let i=s.parent,a=i.type==="VariableDeclaration"?i.kind:"variable";(!t||t===a||t==="variable")&&o.push({name:s.node.id.name,kind:a,line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})}},TSInterfaceDeclaration(s){(!t||t==="interface")&&o.push({name:s.node.id.name,kind:"interface",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})},TSTypeAliasDeclaration(s){(!t||t==="type")&&o.push({name:s.node.id.name,kind:"type",line:s.node.loc?.start.line||0,column:s.node.loc?.start.column||0})}})}catch(r){throw new Error(`Failed to parse file "${e.filePath}": ${r.message}`)}return o}async getImports(e){let t=[];try{let o=this.parseCode(e.content);be(o,{ImportDeclaration(r){let s=r.node.source.value,i=[],a="side-effect";for(let l of r.node.specifiers)if(l.type==="ImportDefaultSpecifier")i.push(l.local.name),a="default";else if(l.type==="ImportNamespaceSpecifier")i.push(`* as ${l.local.name}`),a="namespace";else if(l.type==="ImportSpecifier"){let p=l.imported.type==="Identifier"?l.imported.name:l.imported.value,m=l.local.name;i.push(p===m?p:`${p} as ${m}`),a="named"}t.push({source:s,imports:i,line:r.node.loc?.start.line||0,type:a})}})}catch(o){throw new Error(`Failed to parse file "${e.filePath}": ${o.message}`)}return t}async findReferences(e,t,o){let r=[];try{let s=e.content,i=s.split(`
|
|
143
|
+
`),a=this.parseCode(s);be(a,{Identifier(l){if(l.node.name===t){let p=l.isFunctionDeclaration()||l.isClassDeclaration()||l.parent.type==="VariableDeclarator"&&l.parent.id===l.node||l.parent.type==="TSInterfaceDeclaration"&&l.parent.id===l.node||l.parent.type==="TSTypeAliasDeclaration"&&l.parent.id===l.node;if(!p||o){let m=l.node.loc?.start.line||0,d=l.node.loc?.start.column||0,g=i[m-1]||"";r.push({file:e.filePath,line:m,column:d,context:g.trim(),isDeclaration:p})}}}})}catch{}return r}async getSymbolAtPosition(e,t,o){try{let r=this.parseCode(e.content),s=null;return be(r,{Identifier(i){let a=i.node.loc;a&&a.start.line===t&&a.start.column===o&&(s=i.node.name,i.stop())}}),s}catch{return null}}async getDefinition(e,t){try{let o=this.parseCode(e.content),r=e.filePath,s=null;return be(o,{FunctionDeclaration(i){i.node.id?.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"function",name:t},i.stop())},ClassDeclaration(i){i.node.id?.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"class",name:t},i.stop())},VariableDeclarator(i){if(i.node.id.type==="Identifier"&&i.node.id.name===t){let a=i.parent,l=a.type==="VariableDeclaration"?a.kind:"variable";s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:l,name:t},i.stop()}},TSInterfaceDeclaration(i){i.node.id.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"interface",name:t},i.stop())},TSTypeAliasDeclaration(i){i.node.id.name===t&&(s={file:r,line:i.node.loc?.start.line||0,column:i.node.loc?.start.column||0,kind:"type",name:t},i.stop())}}),s}catch{return null}}async getDiagnostics(e){try{return this.parseCode(e.content),[]}catch(t){return[{message:t.message,line:t.loc?.line||0,column:t.loc?.column||0,severity:"error"}]}}async getExports(e){let t=[];try{let o=this.parseCode(e.content);be(o,{ExportNamedDeclaration(r){if(r.node.declaration)if(r.node.declaration.type==="VariableDeclaration")for(let s of r.node.declaration.declarations)s.id.type==="Identifier"&&t.push({name:s.id.name,kind:"variable",line:s.loc?.start.line||0,column:s.loc?.start.column||0});else r.node.declaration.type==="FunctionDeclaration"&&r.node.declaration.id?t.push({name:r.node.declaration.id.name,kind:"function",line:r.node.declaration.loc?.start.line||0,column:r.node.declaration.loc?.start.column||0}):r.node.declaration.type==="ClassDeclaration"&&r.node.declaration.id&&t.push({name:r.node.declaration.id.name,kind:"class",line:r.node.declaration.loc?.start.line||0,column:r.node.declaration.loc?.start.column||0});else if(r.node.specifiers)for(let s of r.node.specifiers)s.exported.type==="Identifier"&&t.push({name:s.exported.name,kind:"export",line:s.loc?.start.line||0,column:s.loc?.start.column||0})},ExportDefaultDeclaration(r){let s="default",i="default";r.node.declaration.type==="ClassDeclaration"&&r.node.declaration.id?(s=r.node.declaration.id.name,i="class"):r.node.declaration.type==="FunctionDeclaration"&&r.node.declaration.id?(s=r.node.declaration.id.name,i="function"):r.node.declaration.type==="Identifier"&&(s=r.node.declaration.name,i="variable"),t.push({name:s,kind:i,line:r.node.loc?.start.line||0,column:r.node.loc?.start.column||0})}})}catch{}return t}async getOutline(e){let t=[];try{return(await this.getSymbols(e)).map(r=>({name:r.name,kind:r.kind,line:r.line,column:r.column,children:[]}))}catch{}return t}async extractFunction(e,t,o,r,s,i){let a=e.content.split(`
|
|
144
|
+
`),l=Math.max(0,t-1),p=Math.min(a.length,r),m=a.slice(l,p).join(`
|
|
145
|
+
`),d=`
|
|
146
|
+
function ${i}() {
|
|
75
147
|
${m}
|
|
76
148
|
}
|
|
77
|
-
`,
|
|
78
|
-
`),
|
|
79
|
-
`),
|
|
80
|
-
`),
|
|
81
|
-
def ${
|
|
149
|
+
`,g=`${i}();`;return{newFunction:d,replacementCall:g}}async getCallHierarchy(e,t,o){try{let r=this.parseCode(e.content),s=e.filePath,i=null,a="",l=0,p=0;if(be(r,{Function(b){let T=b.node.loc;T&&T.start.line<=t&&T.end&&T.end.line>=t&&(i=b,l=T.start.line,p=T.start.column,b.node.type==="FunctionDeclaration"&&b.node.id?a=b.node.id.name:b.parent.type==="VariableDeclarator"&&b.parent.id.type==="Identifier"?a=b.parent.id.name:b.parent.type==="ClassMethod"||b.parent.type==="ObjectMethod"?b.parent.key.type==="Identifier"&&(a=b.parent.key.name):a="<anonymous>")}}),!i||a==="<anonymous>")return null;let m=[],d=[];be(r,{CallExpression(b){let T=b.node.loc;if(!T||T.start.line<l||T.end&&T.end.line>l+1e3)return;let x=!1,S=b;for(;S;){if(S.isFunction()&&S.node.type==="FunctionDeclaration"&&S.node.id?.name===a){x=!0;break}S=S.parentPath}if(!x)return;let v=b.node.callee,D="<unknown>";v.type==="Identifier"?D=v.name:v.type==="MemberExpression"&&v.property.type==="Identifier"&&(D=v.property.name),D!=="<unknown>"&&d.push({file:s,name:D,line:b.node.loc?.start.line||0,column:b.node.loc?.start.column||0})}}),be(r,{CallExpression(b){let T=b.node.callee,x=!1;if((T.type==="Identifier"&&T.name===a||T.type==="MemberExpression"&&T.property.type==="Identifier"&&T.property.name===a)&&(x=!0),x){let S="<global>",v=b;for(;v;){if(v.isFunction()){v.node.type==="FunctionDeclaration"&&v.node.id?S=v.node.id.name:v.parent.type==="VariableDeclarator"&&v.parent.id.type==="Identifier"?S=v.parent.id.name:(v.parent.type==="ClassMethod"||v.parent.type==="ObjectMethod")&&v.parent.key.type==="Identifier"&&(S=v.parent.key.name);break}v=v.parentPath}m.push({file:s,name:S,line:b.node.loc?.start.line||0,column:b.node.loc?.start.column||0})}}});let g=[...new Map(m.map(b=>[`${b.name}:${b.line}`,b])).values()],w=[...new Map(d.map(b=>[`${b.name}:${b.line}`,b])).values()];return{file:s,name:a,line:l,column:p,callers:g,callees:w}}catch{return null}}}});var nf,sf=h(()=>{"use strict";c();nf={}});var cr,af=h(()=>{"use strict";c();sf();cr=class{constructor(e){this.context=e}context;async executeQuery(e,t){let{tree:o,language:r,grammar:s}=await this.context.getTree(e.filePath,e.content),i=nf[r];if(!i||!i[t])throw new Error(`Query ${t} not found for language ${r}`);let a=i[t],l=s.query(a);return{tree:o,captures:l.captures(o.rootNode)}}async findSymbols(e,t,o){return(await this.getSymbols(e,o)).filter(s=>s.name===t).map(s=>({file:e.filePath,line:s.line,column:s.column,kind:s.kind,name:s.name}))}async getSymbols(e,t){let{captures:o}=await this.executeQuery(e,"symbols"),r=[];for(let s of o)if(s.name.startsWith("name.")){let i=s.name.split(".")[1];(!t||t===i)&&r.push({name:s.node.text,kind:i,line:s.node.startPosition.row+1,column:s.node.startPosition.column})}return r}async getImports(e){let{captures:t}=await this.executeQuery(e,"imports"),o=t.filter(s=>s.name==="import").map(s=>s.node),r=[];for(let s of o)r.push({source:s.text,imports:[s.text],line:s.startPosition.row+1,type:"side-effect"});return r}async findReferences(e,t,o){let{captures:r}=await this.executeQuery(e,"references"),s=e.content.split(`
|
|
150
|
+
`),i=[];for(let a of r)if(a.node.text===t){let l=a.node.parent?.type.includes("definition")||a.node.parent?.type.includes("declaration");if(!l||o){let p=a.node.startPosition.row+1;i.push({file:e.filePath,line:p,column:a.node.startPosition.column,context:s[p-1].trim(),isDeclaration:!!l})}}return i}async getSymbolAtPosition(e,t,o){let{tree:r}=await this.context.getTree(e.filePath,e.content),s=r.rootNode.descendantForPosition({row:t-1,column:o});return s&&s.type==="identifier"?s.text:null}async getDefinition(e,t){let o=await this.findSymbols(e,t);return o.length>0?o[0]:null}async getDiagnostics(e){let{tree:t}=await this.context.getTree(e.filePath,e.content),o=[];function r(s){if(s.hasError()){s.type==="ERROR"&&o.push({message:`Syntax error at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"});for(let i of s.children)r(i)}else s.isMissing&&s.isMissing()&&o.push({message:`Missing ${s.type} at line ${s.startPosition.row+1}`,line:s.startPosition.row+1,column:s.startPosition.column,severity:"error"})}return r(t.rootNode),o}async getExports(e){return[]}async getOutline(e){return(await this.getSymbols(e)).map(o=>({name:o.name,kind:o.kind,line:o.line,column:o.column,children:[]}))}async extractFunction(e,t,o,r,s,i){let a=e.content.split(`
|
|
151
|
+
`),l=Math.max(0,t-1),p=Math.min(a.length,r),m=a.slice(l,p).join(`
|
|
152
|
+
`),d="",g="",w=e.filePath.split(".").pop()?.toLowerCase();return w==="py"||w==="pyi"?(d=`
|
|
153
|
+
def ${i}():
|
|
82
154
|
${m.split(`
|
|
83
|
-
`).map(
|
|
155
|
+
`).map(b=>" "+b).join(`
|
|
84
156
|
`)}
|
|
85
|
-
`,
|
|
86
|
-
func ${
|
|
157
|
+
`,g=`${i}()`):w==="go"?(d=`
|
|
158
|
+
func ${i}() {
|
|
87
159
|
${m}
|
|
88
160
|
}
|
|
89
|
-
`,
|
|
90
|
-
fn ${
|
|
161
|
+
`,g=`${i}()`):w==="rs"?(d=`
|
|
162
|
+
fn ${i}() {
|
|
91
163
|
${m}
|
|
92
164
|
}
|
|
93
|
-
`,
|
|
94
|
-
${
|
|
165
|
+
`,g=`${i}();`):w==="sh"||w==="bash"?(d=`
|
|
166
|
+
${i}() {
|
|
95
167
|
${m}
|
|
96
168
|
}
|
|
97
|
-
`,
|
|
98
|
-
void ${
|
|
169
|
+
`,g=`${i}`):(d=`
|
|
170
|
+
void ${i}() {
|
|
99
171
|
${m}
|
|
100
172
|
}
|
|
101
|
-
`,h=`${a}();`),{newFunction:f,replacementCall:h}}async getCallHierarchy(e,t,r){let o=await this.getSymbolAtPosition(e,t,r);if(!o)return null;let a=(await this.findReferences(e,o,!1)).map(i=>({file:i.file,name:i.context.trim()||"<anonymous>",line:i.line,column:i.column}));return{file:e.filePath,name:o,line:t,column:r,callers:a,callees:[]}}}});var Ao,Nm=g(()=>{"use strict";l();Nn();km();Dm();Ao=class{constructor(e){this.context=e;this.babelParser=new Do,this.treeSitterParser=new No(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(ko(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});import{readFileSync as Uh,statSync as Wh,readdirSync as Gh}from"fs";import{join as Bh,extname as Jh}from"path";var Mo,Am=g(()=>{"use strict";l();X();Mo=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 r=Gh(e,{withFileTypes:!0});for(let o of r){let n=Bh(e,o.name);o.name==="node_modules"||o.name===".git"||o.name==="dist"||o.name==="build"||(o.isDirectory()?t.push(...await this.getAllSupportedFiles(n)):o.isFile()&&this.supportedExtensions.includes(Jh(o.name).toLowerCase())&&t.push(n))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let r of t)await this.updateFile(r);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let r=Wh(e).mtimeMs;if(this.fileMtimes.get(e)===r)return;let o=Uh(e,"utf-8"),n=A.getParser(e);this.removeFileFromIndex(e);let a=await n.getSymbols({filePath:e,content:o});for(let i of a){let c=this.data.symbolLocations.get(i.name);c?c.add(e):this.data.symbolLocations.set(i.name,new Set([e]))}this.fileMtimes.set(e,r)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,r]of this.data.symbolLocations.entries())r.delete(e),r.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let r=this.data.symbolLocations.get(e);return r?Array.from(r):[]}}});var Hh,A,Ye,X=g(()=>{"use strict";l();_m();Nm();Am();Hh=new Eo,A=new Ao(Hh),Ye=new Mo});import{readFileSync as zh,statSync as Kh,readdirSync as Qh}from"fs";import{join as Yh,extname as Vh}from"path";async function Mm(s,e,t){try{let r=zh(s,"utf-8");return await A.getParser(s).findSymbols({filePath:s,content:r},e,t)}catch{return[]}}async function Om(s,e,t){let r=[];try{let o=Qh(s,{withFileTypes:!0});for(let n of o){let a=Yh(s,n.name);if(!(n.name==="node_modules"||n.name===".git"||n.name==="dist")){if(n.isDirectory()){let i=await Om(a,e,t);r.push(...i)}else if(n.isFile()&&Xh.includes(Vh(n.name))){let i=await Mm(a,e,t);r.push(...i)}}}}catch{}return r}async function Zh(s){let e=s.symbol,t=s.path,r=s.kind;if(y(`[coding.find-symbol] execute symbol="${e}" path="${t}" kind=${r??"all"}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let o=Kh(t),n;if(o.isDirectory())n=await Om(t,e,r);else if(o.isFile())n=await Mm(t,e,r);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,locations:n},null,2)}var Xh,zt,On=g(()=>{"use strict";l();Tm();X();k();Xh=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];zt={name:hm,displayName:ym,description:wm,parameters:xm,category:bm,execute:Zh}});var Im,jm,Fm,Lm,qm,Um=g(()=>{"use strict";l();Im="coding.get_symbols",jm="Get Symbols",Fm="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",Lm="coding",qm={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});import{readFileSync as ey}from"fs";async function ty(s){let e=s.file,t=s.kind;if(y(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let r=ey(e,"utf-8"),n=await A.getParser(e).getSymbols({filePath:e,content:r},t);return JSON.stringify({file:e,count:n.length,symbols:n},null,2)}catch(r){throw new Error(`Failed to parse file "${e}": ${r.message}`)}}var Kt,In=g(()=>{"use strict";l();Um();X();k();Kt={name:Im,displayName:jm,description:Fm,parameters:qm,category:Lm,execute:ty}});var Wm,Gm,Bm,Jm,Hm,zm=g(()=>{"use strict";l();Wm="coding.get_imports",Gm="Get Imports",Bm="List all import statements in a JavaScript/TypeScript file",Jm="coding",Hm={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as oy}from"fs";async function ry(s){let e=s.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=oy(e,"utf-8"),o=await A.getParser(e).getImports({filePath:e,content:t});return JSON.stringify({file:e,count:o.length,imports:o},null,2)}catch(t){throw new Error(`Failed to map explicit imports in file "${e}": ${t.message}`)}}var Qt,jn=g(()=>{"use strict";l();zm();X();k();Qt={name:Wm,displayName:Gm,description:Bm,parameters:Hm,category:Jm,execute:ry}});var Km,Qm,Ym,Vm,Xm,Zm=g(()=>{"use strict";l();Km="coding.find_references",Qm="Find References",Ym="Find all references to a symbol across JavaScript/TypeScript files",Vm="coding",Xm={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});import{readFileSync as ny,statSync as sy}from"fs";async function ed(s,e,t){try{let r=ny(s,"utf-8");return await A.getParser(s).findReferences({filePath:s,content:r},e,t)}catch{return[]}}async function iy(s,e,t){let r=[];await Ye.buildIndex(s);let o=await Ye.getDefinitionFiles(e,s);for(let n of o)if(n.startsWith(s)){let a=await ed(n,e,t);r.push(...a)}return r}async function ay(s){let e=s.symbol,t=s.path,r=s.includeDeclaration===!0;if(y(`[coding.find-references] execute symbol="${e}" path="${t}" includeDecl=${r}`),!e)throw new Error("symbol is required");if(!t)throw new Error("path is required");let o=sy(t),n;if(o.isDirectory())n=await iy(t,e,r);else if(o.isFile())n=await ed(t,e,r);else throw new Error(`Path is neither a file nor directory: ${t}`);return JSON.stringify({symbol:e,found:n.length,references:n},null,2)}var Oo,Fn=g(()=>{"use strict";l();Zm();X();k();Oo={name:Km,displayName:Qm,description:Ym,parameters:Xm,category:Vm,execute:ay}});var td,od,rd,nd,sd,id=g(()=>{"use strict";l();td="coding.go_to_definition",od="Go To Definition",rd="Jump to the definition of a symbol at a specific location in a file",nd="coding",sd={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});import{readFileSync as ad,statSync as ly}from"fs";import{dirname as cy}from"path";async function py(s,e,t){try{let r=ad(s,"utf-8");return await A.getParser(s).getSymbolAtPosition({filePath:s,content:r},e,t)}catch{return null}}async function ld(s,e){try{let t=ad(s,"utf-8");return await A.getParser(s).getDefinition({filePath:s,content:t},e)}catch{return null}}async function my(s,e){await Ye.buildIndex(s);let t=await Ye.getDefinitionFiles(e,s);for(let r of t)if(r.startsWith(s)){let o=await ld(r,e);if(o)return o}return null}async function dy(s){let e=s.file,t=s.line,r=s.column,o=s.searchPath;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(r===void 0)throw new Error("column is required");let n=await py(e,t,r);if(!n)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${r}`},null,2);let a=await ld(e,n);if(!a){let i=o||cy(e);ly(i).isDirectory()&&(a=await my(i,n))}return JSON.stringify(a?{found:!0,symbol:n,definition:a}:{found:!1,symbol:n,message:`Definition not found for symbol "${n}"`},null,2)}var Io,Ln=g(()=>{"use strict";l();id();X();Io={name:td,displayName:od,description:rd,parameters:sd,category:nd,execute:dy}});var cd,pd,md,dd,ud,fd=g(()=>{"use strict";l();cd="coding.multi_file_edit",pd="Multi-File Edit",md="Edit multiple files atomically with rollback on failure",dd="coding",ud={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});import{readFileSync as uy,writeFileSync as gd,existsSync as fy}from"fs";async function gy(s){let e=s.edits,t=s.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let n of e){if(!n.file)throw new Error("Each edit must have a file property");if(!n.changes||!Array.isArray(n.changes))throw new Error("Each edit must have a changes array");if(!fy(n.file))throw new Error(`File does not exist: ${n.file}`)}let r=[],o=[];try{for(let n of e){let a=uy(n.file,"utf-8");t&&r.push({file:n.file,content:a});let i=a;for(let c of n.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=(i.match(new RegExp(hy(c.oldText),"g"))||[]).length;if(p===0)throw new Error(`Text not found in ${n.file}: "${c.oldText.substring(0,50)}..."`);if(p>1)throw new Error(`Ambiguous replacement in ${n.file}: "${c.oldText.substring(0,50)}..." appears ${p} times`);i=i.replace(c.oldText,c.newText)}gd(n.file,i,"utf-8"),o.push(n.file)}return JSON.stringify({success:!0,filesModified:o.length,files:o},null,2)}catch(n){if(t&&r.length>0){for(let a of r)try{gd(a.file,a.content,"utf-8")}catch{}throw new Error(`Multi-file edit failed and rolled back: ${n.message}`)}throw new Error(`Multi-file edit failed: ${n.message}`)}}function hy(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var jo,qn=g(()=>{"use strict";l();fd();jo={name:cd,displayName:pd,description:md,parameters:ud,category:dd,execute:gy}});var hd,yd,wd,bd,xd,Td=g(()=>{"use strict";l();hd="coding.refactor_rename",yd="Refactor Rename",wd="Rename a symbol across the entire codebase intelligently",bd="coding",xd={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});import{readFileSync as yy,writeFileSync as wy,readdirSync as by}from"fs";import{join as xy,extname as Ty}from"path";import{parse as Py}from"@babel/parser";import*as Un from"@babel/traverse";function Sy(s,e,t,r){let o=[];try{let n=yy(s,"utf-8"),a=n.split(`
|
|
102
|
-
`),
|
|
103
|
-
`),"utf-8")}}catch{}return{file:s,occurrences:o.length,changes:o}}function Pd(s,e,t,r){let o=[];try{let n=by(s,{withFileTypes:!0});for(let a of n){let i=xy(s,a.name);if(!(a.name==="node_modules"||a.name===".git"||a.name==="dist")){if(a.isDirectory())o.push(...Pd(i,e,t,r));else if(a.isFile()&&vy.includes(Ty(a.name))){let c=Sy(i,e,t,r);c.occurrences>0&&o.push(c)}}}}catch{}return o}async function $y(s){let e=s.symbol,t=s.newName,r=s.path,o=s.dryRun===!0;if(!e)throw new Error("symbol is required");if(!t)throw new Error("newName is required");if(!r)throw new Error("path is required");if(e===t)throw new Error("New name must be different from old name");let n=Pd(r,e,t,o),a=n.reduce((c,p)=>c+p.occurrences,0),i=n.length;return JSON.stringify({success:!0,dryRun:o,oldName:e,newName:t,filesAffected:i,totalOccurrences:a,changes:n},null,2)}var Cy,vy,Fo,Wn=g(()=>{"use strict";l();Td();Cy=Un.default||Un,vy=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];Fo={name:hd,displayName:yd,description:wd,parameters:xd,category:bd,execute:$y}});var Cd,vd,Sd,$d,_d,kd=g(()=>{"use strict";l();Cd="coding.get_outline",vd="Get File Outline",Sd="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",$d="coding",_d={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as _y,statSync as ky}from"fs";async function Ry(s){let e=s.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!ky(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=_y(e,"utf-8"),r=A.getParser(e);if(!r.getOutline)return JSON.stringify({file:e,error:"Outline extraction is not specifically implemented for this language yet."});let o=await r.getOutline({filePath:e,content:t});return JSON.stringify({file:e,outline:o},null,2)}catch(t){throw new Error(`Failed to safely extract outline from file "${e}": ${t.message}`)}}var Lo,Gn=g(()=>{"use strict";l();kd();X();k();Lo={name:Cd,displayName:vd,description:Sd,parameters:_d,category:$d,execute:Ry}});var Rd,Ed,Dd,Nd,Ad,Md=g(()=>{"use strict";l();Rd="coding.get_diagnostics",Ed="Get File Diagnostics",Dd="Gets syntax errors and warnings for a file utilizing AST parsing.",Nd="coding",Ad={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as Ey,statSync as Dy}from"fs";async function Ny(s){let e=s.file;if(!e)throw new Error("file is required");try{if(!Dy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Ey(e,"utf-8"),r=A.getParser(e);if(!r.getDiagnostics)return JSON.stringify({file:e,error:"Diagnostics extraction is not specifically implemented for this language yet."});let o=await r.getDiagnostics({filePath:e,content:t});return JSON.stringify({file:e,diagnostics:o},null,2)}catch(t){throw new Error(`Failed to get diagnostics from file "${e}": ${t.message}`)}}var qo,Bn=g(()=>{"use strict";l();Md();X();qo={name:Rd,displayName:Ed,description:Dd,parameters:Ad,category:Nd,execute:Ny}});var Od,Id,jd,Fd,Ld,qd=g(()=>{"use strict";l();Od="coding.get_exports",Id="Get File Exports",jd="Lists all symbols exported by a file.",Fd="coding",Ld={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as Ay,statSync as My}from"fs";async function Oy(s){let e=s.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!My(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=Ay(e,"utf-8"),r=A.getParser(e);if(!r.getExports)return JSON.stringify({file:e,error:"Exports extraction is not specifically implemented for this language yet."});let o=await r.getExports({filePath:e,content:t});return JSON.stringify({file:e,exports:o},null,2)}catch(t){throw new Error(`Failed to extract exports from file "${e}": ${t.message}`)}}var Uo,Jn=g(()=>{"use strict";l();qd();X();k();Uo={name:Od,displayName:Id,description:jd,parameters:Ld,category:Fd,execute:Oy}});var Ud,Wd,Gd,Bd,Jd,Hd=g(()=>{"use strict";l();Ud="coding.extract_function",Wd="Extract Function",Gd="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Bd="coding",Jd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});import{readFileSync as Iy,statSync as jy}from"fs";async function Fy(s){let e=s.file,t=s.startLine,r=s.startColumn,o=s.endLine,n=s.endColumn,a=s.newFunctionName;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("startLine is required");if(r===void 0)throw new Error("startColumn is required");if(o===void 0)throw new Error("endLine is required");if(n===void 0)throw new Error("endColumn is required");if(!a)throw new Error("newFunctionName is required");try{if(!jy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let i=Iy(e,"utf-8"),c=A.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:i},t,r,o,n,a);return JSON.stringify({file:e,result:p},null,2)}catch(i){throw new Error(`Failed to extract function from file "${e}": ${i.message}`)}}var Wo,Hn=g(()=>{"use strict";l();Hd();X();Wo={name:Ud,displayName:Wd,description:Gd,parameters:Jd,category:Bd,execute:Fy}});var zd,Kd,Qd,Yd,Vd,Xd=g(()=>{"use strict";l();zd="coding.get_call_hierarchy",Kd="Get Call Hierarchy",Qd="Shows callers and callees of a specific function or method.",Yd="coding",Vd={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});import{readFileSync as Ly,statSync as qy}from"fs";async function Uy(s){let e=s.file,t=s.line,r=s.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(r===void 0)throw new Error("column is required");try{if(!qy(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let o=Ly(e,"utf-8"),n=A.getParser(e);if(!n.getCallHierarchy)return JSON.stringify({file:e,error:"Call hierarchy is not specifically implemented for this language yet."});let a=await n.getCallHierarchy({filePath:e,content:o},t,r);return JSON.stringify({file:e,hierarchy:a},null,2)}catch(o){throw new Error(`Failed to get call hierarchy from file "${e}": ${o.message}`)}}var Go,zn=g(()=>{"use strict";l();Xd();X();Go={name:zd,displayName:Kd,description:Qd,parameters:Vd,category:Yd,execute:Uy}});var eu={};re(eu,{codingExtractFunctionTool:()=>Wo,codingFindReferencesTool:()=>Oo,codingFindSymbolTool:()=>zt,codingGetCallHierarchyTool:()=>Go,codingGetDiagnosticsTool:()=>qo,codingGetExportsTool:()=>Uo,codingGetImportsTool:()=>Qt,codingGetOutlineTool:()=>Lo,codingGetSymbolsTool:()=>Kt,codingGoToDefinitionTool:()=>Io,codingMultiFileEditTool:()=>jo,codingRefactorRenameTool:()=>Fo,codingToolsProject:()=>Zd});var Zd,Kn=g(()=>{"use strict";l();On();In();jn();Fn();Ln();qn();Wn();Gn();Bn();Jn();Hn();zn();On();In();jn();Fn();Ln();qn();Wn();Gn();Bn();Jn();Hn();zn();Zd={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:[zt,Kt,Qt,Oo,Io,Lo,qo,Uo,Wo,Go,jo,Fo],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var tu,ou=g(()=>{"use strict";l();tu={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});import{simpleGit as Wy}from"simple-git";function q(s){let e={baseDir:s||process.cwd(),binary:"git",maxConcurrentProcesses:6};return Wy(e)}var ie=g(()=>{"use strict";l()});var Bo,ru=g(()=>{"use strict";l();ou();ie();Bo={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:tu,execute:async s=>{let e=s.path;try{let r=await q().status(e?[e]:[]);if(r.isClean())return"Working tree clean";let o=[];return o.push(`Branch: ${r.current}`),r.tracking&&o.push(`Tracking: ${r.tracking}`),r.ahead>0&&o.push(`Ahead: ${r.ahead}`),r.behind>0&&o.push(`Behind: ${r.behind}`),o.push("---"),r.conflicted.length>0&&o.push(`Conflicted: ${r.conflicted.join(", ")}`),r.created.length>0&&o.push(`Created: ${r.created.join(", ")}`),r.deleted.length>0&&o.push(`Deleted: ${r.deleted.join(", ")}`),r.modified.length>0&&o.push(`Modified: ${r.modified.join(", ")}`),r.renamed.length>0&&o.push(`Renamed: ${r.renamed.map(n=>`${n.from} -> ${n.to}`).join(", ")}`),r.staged.length>0&&o.push(`Staged: ${r.staged.join(", ")}`),r.not_added.length>0&&o.push(`Untracked: ${r.not_added.join(", ")}`),o.join(`
|
|
104
|
-
`)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var
|
|
105
|
-
Author: ${
|
|
106
|
-
Date: ${
|
|
107
|
-
Message: ${
|
|
173
|
+
`,g=`${i}();`),{newFunction:d,replacementCall:g}}async getCallHierarchy(e,t,o){let r=await this.getSymbolAtPosition(e,t,o);if(!r)return null;let i=(await this.findReferences(e,r,!1)).map(a=>({file:a.file,name:a.context.trim()||"<anonymous>",line:a.line,column:a.column}));return{file:e.filePath,name:r,line:t,column:o,callers:i,callees:[]}}}});var pr,lf=h(()=>{"use strict";c();$s();rf();af();pr=class{constructor(e){this.context=e;this.babelParser=new lr,this.treeSitterParser=new cr(this.context)}context;babelParser;treeSitterParser;getParser(e){switch(sr(e)){case"javascript":case"typescript":case"tsx":case"jsx":return this.babelParser;case"python":case"go":case"rust":case"java":case"c":case"cpp":return this.treeSitterParser;default:throw new Error(`Unsupported or unknown language for file: ${e}`)}}}});import{readFileSync as jw,statSync as Fw,readdirSync as qw}from"fs";import{join as Ww,extname as Uw}from"path";var mr,cf=h(()=>{"use strict";c();ie();mr=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=qw(e,{withFileTypes:!0});for(let r of o){let s=Ww(e,r.name);r.name==="node_modules"||r.name===".git"||r.name==="dist"||r.name==="build"||(r.isDirectory()?t.push(...await this.getAllSupportedFiles(s)):r.isFile()&&this.supportedExtensions.includes(Uw(r.name).toLowerCase())&&t.push(s))}}catch{}return t}async buildIndex(e){if(!(this.isBuilt||this.isBuilding)){this.isBuilding=!0;try{let t=await this.getAllSupportedFiles(e);for(let o of t)await this.updateFile(o);this.isBuilt=!0}finally{this.isBuilding=!1}}}async updateFile(e){try{let o=Fw(e).mtimeMs;if(this.fileMtimes.get(e)===o)return;let r=jw(e,"utf-8"),s=L.getParser(e);this.removeFileFromIndex(e);let i=await s.getSymbols({filePath:e,content:r});for(let a of i){let l=this.data.symbolLocations.get(a.name);l?l.add(e):this.data.symbolLocations.set(a.name,new Set([e]))}this.fileMtimes.set(e,o)}catch{this.removeFileFromIndex(e)}}removeFileFromIndex(e){for(let[t,o]of this.data.symbolLocations.entries())o.delete(e),o.size===0&&this.data.symbolLocations.delete(t);this.fileMtimes.delete(e)}async getDefinitionFiles(e,t){await this.buildIndex(t);let o=this.data.symbolLocations.get(e);return o?Array.from(o):[]}}});var Gw,L,mt,ie=h(()=>{"use strict";c();of();lf();cf();Gw=new ar,L=new pr(Gw),mt=new mr});import{readFileSync as Bw,statSync as zw,readdirSync as Hw}from"fs";import{join as Kw,extname as Jw}from"path";async function pf(n,e,t){try{let o=Bw(n,"utf-8");return await L.getParser(n).findSymbols({filePath:n,content:o},e,t)}catch{return[]}}async function mf(n,e,t){let o=[];try{let r=Hw(n,{withFileTypes:!0});for(let s of r){let i=Kw(n,s.name);if(!(s.name==="node_modules"||s.name===".git"||s.name==="dist")){if(s.isDirectory()){let a=await mf(i,e,t);o.push(...a)}else if(s.isFile()&&Qw.includes(Jw(s.name))){let a=await pf(i,e,t);o.push(...a)}}}}catch{}return o}async function Vw(n){let e=n.symbol,t=n.path,o=n.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 r=zw(t),s;if(r.isDirectory())s=await mf(t,e,o);else if(r.isFile())s=await pf(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 Qw,vo,Ds=h(()=>{"use strict";c();Vu();ie();P();Qw=[".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".c",".cpp",".h",".hpp"];vo={name:zu,displayName:Hu,description:Ku,parameters:Qu,category:Ju,execute:Vw}});var df,uf,ff,gf,hf,yf=h(()=>{"use strict";c();df="coding.get_symbols",uf="Get Symbols",ff="List all symbols (functions, classes, variables, etc.) in a JavaScript/TypeScript file",gf="coding",hf={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"},kind:{type:"string",description:"Optional: filter by symbol kind (function, class, variable, const, let, interface, type)"}},required:["file"]}});import{readFileSync as Xw}from"fs";async function Yw(n){let e=n.file,t=n.kind;if(y(`[coding.get-symbols] execute file="${e}" kind=${t??"all"}`),!e)throw new Error("file is required");try{let o=Xw(e,"utf-8"),s=await L.getParser(e).getSymbols({filePath:e,content:o},t);return JSON.stringify({file:e,count:s.length,symbols:s},null,2)}catch(o){throw new Error(`Failed to parse file "${e}": ${o.message}`)}}var Co,Ms=h(()=>{"use strict";c();yf();ie();P();Co={name:df,displayName:uf,description:ff,parameters:hf,category:gf,execute:Yw}});var bf,wf,Tf,xf,vf,Cf=h(()=>{"use strict";c();bf="coding.get_imports",wf="Get Imports",Tf="List all import statements in a JavaScript/TypeScript file",xf="coding",vf={type:"object",properties:{file:{type:"string",description:"Path to the file to analyze"}},required:["file"]}});import{readFileSync as Zw}from"fs";async function eT(n){let e=n.file;if(y(`[coding.get-imports] execute file="${e}"`),!e)throw new Error("file is required");try{let t=Zw(e,"utf-8"),r=await L.getParser(e).getImports({filePath:e,content:t});return JSON.stringify({file:e,count:r.length,imports:r},null,2)}catch(t){throw new Error(`Failed to map explicit imports in file "${e}": ${t.message}`)}}var Po,Ns=h(()=>{"use strict";c();Cf();ie();P();Po={name:bf,displayName:wf,description:Tf,parameters:vf,category:xf,execute:eT}});var Pf,Sf,kf,Rf,$f,_f=h(()=>{"use strict";c();Pf="coding.find_references",Sf="Find References",kf="Find all references to a symbol across JavaScript/TypeScript files",Rf="coding",$f={type:"object",properties:{symbol:{type:"string",description:"Name of the symbol to find references for"},path:{type:"string",description:"File or directory path to search in (searches recursively if directory)"},includeDeclaration:{type:"boolean",description:"Include the symbol declaration in results (default: false)"}},required:["symbol","path"]}});import{readFileSync as tT,statSync as oT}from"fs";async function Ef(n,e,t){try{let o=tT(n,"utf-8");return await L.getParser(n).findReferences({filePath:n,content:o},e,t)}catch{return[]}}async function rT(n,e,t){let o=[];await mt.buildIndex(n);let r=await mt.getDefinitionFiles(e,n);for(let s of r)if(s.startsWith(n)){let i=await Ef(s,e,t);o.push(...i)}return o}async function nT(n){let e=n.symbol,t=n.path,o=n.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 r=oT(t),s;if(r.isDirectory())s=await rT(t,e,o);else if(r.isFile())s=await Ef(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 dr,As=h(()=>{"use strict";c();_f();ie();P();dr={name:Pf,displayName:Sf,description:kf,parameters:$f,category:Rf,execute:nT}});var Df,Mf,Nf,Af,Of,If=h(()=>{"use strict";c();Df="coding.go_to_definition",Mf="Go To Definition",Nf="Jump to the definition of a symbol at a specific location in a file",Af="coding",Of={type:"object",properties:{file:{type:"string",description:"Path to the file containing the symbol reference"},line:{type:"integer",description:"Line number where the symbol is referenced (1-indexed)"},column:{type:"integer",description:"Column number where the symbol is referenced (0-indexed)"},searchPath:{type:"string",description:"Optional: directory to search for the definition (defaults to file directory)"}},required:["file","line","column"]}});import{readFileSync as Lf,statSync as sT}from"fs";import{dirname as iT}from"path";async function aT(n,e,t){try{let o=Lf(n,"utf-8");return await L.getParser(n).getSymbolAtPosition({filePath:n,content:o},e,t)}catch{return null}}async function jf(n,e){try{let t=Lf(n,"utf-8");return await L.getParser(n).getDefinition({filePath:n,content:t},e)}catch{return null}}async function lT(n,e){await mt.buildIndex(n);let t=await mt.getDefinitionFiles(e,n);for(let o of t)if(o.startsWith(n)){let r=await jf(o,e);if(r)return r}return null}async function cT(n){let e=n.file,t=n.line,o=n.column,r=n.searchPath;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");let s=await aT(e,t,o);if(!s)return JSON.stringify({found:!1,message:`No symbol found at ${e}:${t}:${o}`},null,2);let i=await jf(e,s);if(!i){let a=r||iT(e);sT(a).isDirectory()&&(i=await lT(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 ur,Os=h(()=>{"use strict";c();If();ie();ur={name:Df,displayName:Mf,description:Nf,parameters:Of,category:Af,execute:cT}});var Ff,qf,Wf,Uf,Gf,Bf=h(()=>{"use strict";c();Ff="coding.multi_file_edit",qf="Multi-File Edit",Wf="Edit multiple files atomically with rollback on failure",Uf="coding",Gf={type:"object",properties:{edits:{type:"array",items:{type:"object",properties:{file:{type:"string"},changes:{type:"array",items:{type:"object",properties:{oldText:{type:"string"},newText:{type:"string"}}}}}},description:"Array of file edits, each with file path and array of text replacements"},atomic:{type:"boolean",description:"Atomic mode: rollback all edits if any fails (default: true)"}},required:["edits"]}});import{readFileSync as pT,writeFileSync as zf,existsSync as mT}from"fs";async function dT(n){let e=n.edits,t=n.atomic!==!1;if(!e||!Array.isArray(e)||e.length===0)throw new Error("edits array is required and must not be empty");for(let s of e){if(!s.file)throw new Error("Each edit must have a file property");if(!s.changes||!Array.isArray(s.changes))throw new Error("Each edit must have a changes array");if(!mT(s.file))throw new Error(`File does not exist: ${s.file}`)}let o=[],r=[];try{for(let s of e){let i=pT(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(uT(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)}zf(s.file,a,"utf-8"),r.push(s.file)}return JSON.stringify({success:!0,filesModified:r.length,files:r},null,2)}catch(s){if(t&&o.length>0){for(let i of o)try{zf(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 uT(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var fr,Is=h(()=>{"use strict";c();Bf();fr={name:Ff,displayName:qf,description:Wf,parameters:Gf,category:Uf,execute:dT,confirmation:{level:"high",reason:"This will modify multiple source code files atomically.",showArgs:["edits"]}}});var Hf,Kf,Jf,Qf,Vf,Xf=h(()=>{"use strict";c();Hf="coding.refactor_rename",Kf="Refactor Rename",Jf="Rename a symbol across the entire codebase intelligently",Qf="coding",Vf={type:"object",properties:{symbol:{type:"string",description:"Current name of the symbol to rename"},newName:{type:"string",description:"New name for the symbol"},path:{type:"string",description:"Directory path to search and rename in"},dryRun:{type:"boolean",description:"Preview changes without applying them (default: false)"}},required:["symbol","newName","path"]}});import{readFileSync as fT,writeFileSync as gT,readdirSync as hT}from"fs";import{join as yT,extname as bT}from"path";import{parse as wT}from"@babel/parser";import*as Ls from"@babel/traverse";function vT(n,e,t,o){let r=[];try{let s=fT(n,"utf-8"),i=s.split(`
|
|
174
|
+
`),a=wT(s,{sourceType:"module",plugins:["jsx","typescript","decorators-legacy","classProperties","objectRestSpread","optionalChaining","nullishCoalescingOperator"]}),l=[];if(TT(a,{Identifier(p){if(p.node.name===e){let m=p.node.loc?.start.line||0,d=p.node.loc?.start.column||0;l.push({line:m,column:d,length:e.length}),r.push({file:n,line:m,column:d,oldName:e,newName:t})}}}),!o&&l.length>0){l.sort((m,d)=>m.line!==d.line?d.line-m.line:d.column-m.column);let p=[...i];for(let m of l){let d=m.line-1;if(d>=0&&d<p.length){let g=p[d],w=g.substring(0,m.column),b=g.substring(m.column+m.length);p[d]=w+t+b}}gT(n,p.join(`
|
|
175
|
+
`),"utf-8")}}catch{}return{file:n,occurrences:r.length,changes:r}}function Yf(n,e,t,o){let r=[];try{let s=hT(n,{withFileTypes:!0});for(let i of s){let a=yT(n,i.name);if(!(i.name==="node_modules"||i.name===".git"||i.name==="dist")){if(i.isDirectory())r.push(...Yf(a,e,t,o));else if(i.isFile()&&xT.includes(bT(i.name))){let l=vT(a,e,t,o);l.occurrences>0&&r.push(l)}}}}catch{}return r}async function CT(n){let e=n.symbol,t=n.newName,o=n.path,r=n.dryRun===!0;if(!e)throw new Error("symbol is required");if(!t)throw new Error("newName is required");if(!o)throw new Error("path is required");if(e===t)throw new Error("New name must be different from old name");let s=Yf(o,e,t,r),i=s.reduce((l,p)=>l+p.occurrences,0),a=s.length;return JSON.stringify({success:!0,dryRun:r,oldName:e,newName:t,filesAffected:a,totalOccurrences:i,changes:s},null,2)}var TT,xT,gr,js=h(()=>{"use strict";c();Xf();TT=Ls.default||Ls,xT=[".js",".jsx",".ts",".tsx",".mjs",".cjs"];gr={name:Hf,displayName:Kf,description:Jf,parameters:Vf,category:Qf,execute:CT,confirmation:{level:"high",reason:"This will rename a symbol across multiple files, rewriting source code without backup.",showArgs:["symbol","newName"]}}});var Zf,eg,tg,og,rg,ng=h(()=>{"use strict";c();Zf="coding.get_outline",eg="Get File Outline",tg="Gets a hierarchical outline of symbols (classes, functions, methods) in a specified file.",og="coding",rg={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to outline"}},required:["file"]}});import{readFileSync as PT,statSync as ST}from"fs";async function kT(n){let e=n.file;if(y(`[coding.get-outline] execute file="${e}"`),!e)throw new Error("file is required");try{if(!ST(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=PT(e,"utf-8"),o=L.getParser(e);if(!o.getOutline)return JSON.stringify({file:e,error:"Outline extraction is not specifically implemented for this language yet."});let r=await o.getOutline({filePath:e,content:t});return JSON.stringify({file:e,outline:r},null,2)}catch(t){throw new Error(`Failed to safely extract outline from file "${e}": ${t.message}`)}}var hr,Fs=h(()=>{"use strict";c();ng();ie();P();hr={name:Zf,displayName:eg,description:tg,parameters:rg,category:og,execute:kT}});var sg,ig,ag,lg,cg,pg=h(()=>{"use strict";c();sg="coding.get_diagnostics",ig="Get File Diagnostics",ag="Gets syntax errors and warnings for a file utilizing AST parsing.",lg="coding",cg={type:"object",properties:{file:{type:"string",description:"The absolute path to the file to check for diagnostics"}},required:["file"]}});import{readFileSync as RT,statSync as $T}from"fs";async function _T(n){let e=n.file;if(!e)throw new Error("file is required");try{if(!$T(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=RT(e,"utf-8"),o=L.getParser(e);if(!o.getDiagnostics)return JSON.stringify({file:e,error:"Diagnostics extraction is not specifically implemented for this language yet."});let r=await o.getDiagnostics({filePath:e,content:t});return JSON.stringify({file:e,diagnostics:r},null,2)}catch(t){throw new Error(`Failed to get diagnostics from file "${e}": ${t.message}`)}}var yr,qs=h(()=>{"use strict";c();pg();ie();yr={name:sg,displayName:ig,description:ag,parameters:cg,category:lg,execute:_T}});var mg,dg,ug,fg,gg,hg=h(()=>{"use strict";c();mg="coding.get_exports",dg="Get File Exports",ug="Lists all symbols exported by a file.",fg="coding",gg={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"}},required:["file"]}});import{readFileSync as ET,statSync as DT}from"fs";async function MT(n){let e=n.file;if(y(`[coding.get-exports] execute file="${e}"`),!e)throw new Error("file is required");try{if(!DT(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let t=ET(e,"utf-8"),o=L.getParser(e);if(!o.getExports)return JSON.stringify({file:e,error:"Exports extraction is not specifically implemented for this language yet."});let r=await o.getExports({filePath:e,content:t});return JSON.stringify({file:e,exports:r},null,2)}catch(t){throw new Error(`Failed to extract exports from file "${e}": ${t.message}`)}}var br,Ws=h(()=>{"use strict";c();hg();ie();P();br={name:mg,displayName:dg,description:ug,parameters:gg,category:fg,execute:MT}});var yg,bg,wg,Tg,xg,vg=h(()=>{"use strict";c();yg="coding.extract_function",bg="Extract Function",wg="Extracts a selected code region into a new function, automatically detecting required parameters and return values.",Tg="coding",xg={type:"object",properties:{file:{type:"string",description:"The absolute path to the file"},startLine:{type:"number",description:"1-indexed start line of the code to extract"},startColumn:{type:"number",description:"0-indexed start column of the code to extract"},endLine:{type:"number",description:"1-indexed end line of the code to extract"},endColumn:{type:"number",description:"0-indexed end column of the code to extract"},newFunctionName:{type:"string",description:"The name for the newly extracted function"}},required:["file","startLine","startColumn","endLine","endColumn","newFunctionName"]}});import{readFileSync as NT,statSync as AT}from"fs";async function OT(n){let e=n.file,t=n.startLine,o=n.startColumn,r=n.endLine,s=n.endColumn,i=n.newFunctionName;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("startLine is required");if(o===void 0)throw new Error("startColumn is required");if(r===void 0)throw new Error("endLine is required");if(s===void 0)throw new Error("endColumn is required");if(!i)throw new Error("newFunctionName is required");try{if(!AT(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let a=NT(e,"utf-8"),l=L.getParser(e);if(!l.extractFunction)return JSON.stringify({file:e,error:"Function extraction is not specifically implemented for this language yet."});let p=await l.extractFunction({filePath:e,content:a},t,o,r,s,i);return JSON.stringify({file:e,result:p},null,2)}catch(a){throw new Error(`Failed to extract function from file "${e}": ${a.message}`)}}var wr,Us=h(()=>{"use strict";c();vg();ie();wr={name:yg,displayName:bg,description:wg,parameters:xg,category:Tg,execute:OT}});var Cg,Pg,Sg,kg,Rg,$g=h(()=>{"use strict";c();Cg="coding.get_call_hierarchy",Pg="Get Call Hierarchy",Sg="Shows callers and callees of a specific function or method.",kg="coding",Rg={type:"object",properties:{file:{type:"string",description:"The absolute path to the file containing the function"},line:{type:"number",description:"1-indexed line number where the function is defined or called"},column:{type:"number",description:"0-indexed column number where the function is defined or called"}},required:["file","line","column"]}});import{readFileSync as IT,statSync as LT}from"fs";async function jT(n){let e=n.file,t=n.line,o=n.column;if(!e)throw new Error("file is required");if(t===void 0)throw new Error("line is required");if(o===void 0)throw new Error("column is required");try{if(!LT(e).isFile())throw new Error(`Path is not a file: ${e}`)}catch{throw new Error(`File not found: ${e}`)}try{let r=IT(e,"utf-8"),s=L.getParser(e);if(!s.getCallHierarchy)return JSON.stringify({file:e,error:"Call hierarchy is not specifically implemented for this language yet."});let i=await s.getCallHierarchy({filePath:e,content:r},t,o);return JSON.stringify({file:e,hierarchy:i},null,2)}catch(r){throw new Error(`Failed to get call hierarchy from file "${e}": ${r.message}`)}}var Tr,Gs=h(()=>{"use strict";c();$g();ie();Tr={name:Cg,displayName:Pg,description:Sg,parameters:Rg,category:kg,execute:jT}});var Eg={};re(Eg,{codingExtractFunctionTool:()=>wr,codingFindReferencesTool:()=>dr,codingFindSymbolTool:()=>vo,codingGetCallHierarchyTool:()=>Tr,codingGetDiagnosticsTool:()=>yr,codingGetExportsTool:()=>br,codingGetImportsTool:()=>Po,codingGetOutlineTool:()=>hr,codingGetSymbolsTool:()=>Co,codingGoToDefinitionTool:()=>ur,codingMultiFileEditTool:()=>fr,codingRefactorRenameTool:()=>gr,codingToolsProject:()=>_g});var _g,Bs=h(()=>{"use strict";c();Ds();Ms();Ns();As();Os();Is();js();Fs();qs();Ws();Us();Gs();Ds();Ms();Ns();As();Os();Is();js();Fs();qs();Ws();Us();Gs();_g={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,Co,Po,dr,ur,hr,yr,br,wr,Tr,fr,gr],dependencies:{"@babel/parser":"^7.24.0","@babel/traverse":"^7.24.0","@babel/types":"^7.24.0"}}});var Dg,Mg=h(()=>{"use strict";c();Dg={type:"object",properties:{path:{type:"string",description:"Optional path or directory to check the status for. If omitted, checks the entire repository."}}}});import{simpleGit as FT}from"simple-git";function z(n){let e={baseDir:n||process.cwd(),binary:"git",maxConcurrentProcesses:6};return FT(e)}var we=h(()=>{"use strict";c()});var xr,Ng=h(()=>{"use strict";c();Mg();we();xr={name:"git.status",displayName:"Git Status",description:"Get the working tree status, including modified, staged, and untracked files.",category:"version-control",parameters:Dg,execute:async n=>{let e=n.path;try{let o=await z().status(e?[e]:[]);if(o.isClean())return"Working tree clean";let r=[];return r.push(`Branch: ${o.current}`),o.tracking&&r.push(`Tracking: ${o.tracking}`),o.ahead>0&&r.push(`Ahead: ${o.ahead}`),o.behind>0&&r.push(`Behind: ${o.behind}`),r.push("---"),o.conflicted.length>0&&r.push(`Conflicted: ${o.conflicted.join(", ")}`),o.created.length>0&&r.push(`Created: ${o.created.join(", ")}`),o.deleted.length>0&&r.push(`Deleted: ${o.deleted.join(", ")}`),o.modified.length>0&&r.push(`Modified: ${o.modified.join(", ")}`),o.renamed.length>0&&r.push(`Renamed: ${o.renamed.map(s=>`${s.from} -> ${s.to}`).join(", ")}`),o.staged.length>0&&r.push(`Staged: ${o.staged.join(", ")}`),o.not_added.length>0&&r.push(`Untracked: ${o.not_added.join(", ")}`),r.join(`
|
|
176
|
+
`)}catch(t){return`Error getting git status: ${t instanceof Error?t.message:String(t)}`}}}});var Ag,Og=h(()=>{"use strict";c();Ag={type:"object",properties:{path:{type:"string",description:"Optional path to get the diff for. If omitted, gets the diff for the entire repository."},staged:{type:"boolean",description:"If true, gets the diff of staged changes instead of unstaged changes.",default:!1}}}});var vr,Ig=h(()=>{"use strict";c();Og();we();vr={name:"git.diff",displayName:"Git Diff",description:"Show changes between commits, commit and working tree, etc.",category:"version-control",parameters:Ag,execute:async n=>{let e=n.path,t=n.staged;try{let o=z(),r=[];t&&r.push("--cached"),e&&r.push("--",e);let s=await o.diff(r);return s||"No changes found."}catch(o){return`Error getting git diff: ${o instanceof Error?o.message:String(o)}`}}}});var Lg,jg=h(()=>{"use strict";c();Lg={type:"object",properties:{maxCount:{type:"number",description:"Maximum number of commits to return. Defaults to 10 to prevent large outputs.",default:10},path:{type:"string",description:"Optional path to get the log for specific file or directory."}}}});var Cr,Fg=h(()=>{"use strict";c();jg();we();Cr={name:"git.log",displayName:"Git Log",description:"Show commit logs.",category:"version-control",parameters:Lg,execute:async n=>{let e=n.maxCount||10,t=n.path;try{let o=z(),r={maxCount:e};t&&(r.file=t);let s=await o.log(r);return s.all.length===0?"No commits found.":s.all.map(i=>`Commit: ${i.hash}
|
|
177
|
+
Author: ${i.author_name} <${i.author_email}>
|
|
178
|
+
Date: ${i.date}
|
|
179
|
+
Message: ${i.message}
|
|
108
180
|
`).join(`---
|
|
109
|
-
`)}catch(
|
|
110
|
-
Commit: ${
|
|
111
|
-
Branch: ${
|
|
112
|
-
Summary: ${
|
|
181
|
+
`)}catch(o){return`Error getting git log: ${o instanceof Error?o.message:String(o)}`}}}});var qg,Wg=h(()=>{"use strict";c();qg={type:"object",properties:{path:{type:"string",description:"Path to the file or directory to stage. To stage all changes, use '.'."}},required:["path"]}});var Pr,Ug=h(()=>{"use strict";c();Wg();we();Pr={name:"git.add",displayName:"Git Add",description:"Add file contents to the index (stage changes).",category:"version-control",parameters:qg,execute:async n=>{let e=n.path;try{return await z().add(e),`Successfully staged changes for: ${e}`}catch(t){return`Error staging changes: ${t instanceof Error?t.message:String(t)}`}}}});var Gg,Bg=h(()=>{"use strict";c();Gg={type:"object",properties:{message:{type:"string",description:"The commit message."}},required:["message"]}});var Sr,zg=h(()=>{"use strict";c();Bg();we();Sr={name:"git.commit",displayName:"Git Commit",description:"Record changes to the repository.",category:"version-control",parameters:Gg,execute:async n=>{let e=n.message;try{let o=await z().commit(e);return o.commit?`Successfully committed changes.
|
|
182
|
+
Commit: ${o.commit}
|
|
183
|
+
Branch: ${o.branch}
|
|
184
|
+
Summary: ${o.summary.changes} changes, ${o.summary.insertions} insertions, ${o.summary.deletions} deletions.`:"Nothing to commit."}catch(t){return`Error committing changes: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will create a permanent commit in the repository history.",showArgs:["message"]}}});var Hg,Kg=h(()=>{"use strict";c();Hg={type:"object",properties:{path:{type:"string",description:"Path to the file to blame."}},required:["path"]}});var kr,Jg=h(()=>{"use strict";c();Kg();we();kr={name:"git.blame",displayName:"Git Blame",description:"Show what revision and author last modified each line of a file.",category:"version-control",parameters:Hg,execute:async n=>{let e=n.path;try{return await z().raw(["blame",e])}catch(t){return`Error running git blame: ${t instanceof Error?t.message:String(t)}`}}}});var Qg,Vg=h(()=>{"use strict";c();Qg={type:"object",properties:{remote:{type:"boolean",description:"List remote branches as well.",default:!1}}}});var Rr,Xg=h(()=>{"use strict";c();Vg();we();Rr={name:"git.branch_list",displayName:"Git Branch List",description:"List all branches.",category:"version-control",parameters:Qg,execute:async n=>{let e=n.remote;try{let t=z(),o=e?["-a"]:[],r=await t.branch(o);return`Current Branch: ${r.current}
|
|
113
185
|
|
|
114
186
|
Branches:
|
|
115
|
-
${
|
|
116
|
-
`)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var
|
|
187
|
+
${r.all.join(`
|
|
188
|
+
`)}`}catch(t){return`Error listing branches: ${t instanceof Error?t.message:String(t)}`}}}});var Yg,Zg=h(()=>{"use strict";c();Yg={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 $r,eh=h(()=>{"use strict";c();Zg();we();$r={name:"git.branch_create",displayName:"Git Branch Create",description:"Create a new branch.",category:"version-control",parameters:Yg,execute:async n=>{let e=n.name,t=n.checkout,o=n.startPoint;try{let r=z();return t?(o?await r.checkoutBranch(e,o):await r.checkoutLocalBranch(e),`Successfully created and switched to branch: ${e}`):(o?await r.branch([e,o]):await r.branch([e]),`Successfully created branch: ${e}`)}catch(r){return`Error creating branch: ${r instanceof Error?r.message:String(r)}`}}}});var th,oh=h(()=>{"use strict";c();th={type:"object",properties:{branch:{type:"string",description:"Name of the branch or commit to checkout."}},required:["branch"]}});var _r,rh=h(()=>{"use strict";c();oh();we();_r={name:"git.checkout",displayName:"Git Checkout",description:"Switch branches or restore working tree files.",category:"version-control",parameters:th,execute:async n=>{let e=n.branch;try{return await z().checkout(e),`Successfully checked out: ${e}`}catch(t){return`Error checking out branch: ${t instanceof Error?t.message:String(t)}`}},confirmation:{level:"medium",reason:"This will switch branches, potentially losing uncommitted changes.",showArgs:["branch"]}}});var sh={};re(sh,{gitAddTool:()=>Pr,gitBlameTool:()=>kr,gitBranchCreateTool:()=>$r,gitBranchListTool:()=>Rr,gitCheckoutTool:()=>_r,gitCommitTool:()=>Sr,gitDiffTool:()=>vr,gitLogTool:()=>Cr,gitStatusTool:()=>xr,gitToolsProject:()=>nh});var nh,zs=h(()=>{"use strict";c();Ng();Ig();Fg();Ug();zg();Jg();Xg();eh();rh();nh={manifest:{key:"git",name:"git-tools",displayName:"Git Version Control",version:"1.0.0",description:"Git operations for reading repository state, checking diffs, creating commits, and managing branches.",author:"Sajeer",tools:["git.status","git.diff","git.log","git.add","git.commit","git.blame","git.branch_list","git.branch_create","git.checkout"],category:"version-control"},tools:[xr,vr,Cr,Pr,Sr,kr,Rr,$r,_r],dependencies:{"simple-git":"^3.27.0"}}});var ih,ah=h(()=>{"use strict";c();ih={type:"object",properties:{oldContent:{type:"string",description:"The original text content."},newContent:{type:"string",description:"The new text content."},fileName:{type:"string",description:"Optional filename to include in the patch header."},contextLines:{type:"number",description:"Number of context lines to include around differences. Default is 4.",default:4}},required:["oldContent","newContent"]}});import*as lh from"diff";var Er,ch=h(()=>{"use strict";c();ah();P();Er={name:"diff.create",displayName:"Create Diff",description:"Generate a unified diff from two text contents.",category:"diff",parameters:ih,execute:async n=>{let e=n.oldContent,t=n.newContent,o=n.fileName||"file",r=n.contextLines??4;y(`[diff.create] execute fileName="${o}" contextLines=${r}`);try{return lh.createPatch(o,e,t,"","",{context:r})}catch(s){return`Error creating diff: ${s instanceof Error?s.message:String(s)}`}}}});var ph,mh=h(()=>{"use strict";c();ph={type:"object",properties:{path:{type:"string",description:"Path to the file to patch."},patch:{type:"string",description:"Unified diff string to apply."}},required:["path","patch"]}});import*as uh from"diff";import{promises as dh}from"fs";var Dr,fh=h(()=>{"use strict";c();mh();P();Dr={name:"diff.apply",displayName:"Apply Diff",description:"Apply a unified diff patch to a file.",category:"diff",parameters:ph,execute:async n=>{let e=n.path,t=n.patch;y(`[diff.apply] execute path="${e}"`);try{let o=await dh.readFile(e,"utf8"),r=uh.applyPatch(o,t);return r===!1?"Failed to apply patch. The patch may be malformed or conflicting with the current file content.":(await dh.writeFile(e,r,"utf8"),`Successfully applied patch to ${e}`)}catch(o){return`Error applying patch: ${o instanceof Error?o.message:String(o)}`}},confirmation:{level:"high",reason:"This will apply a patch to files, which may corrupt them if the patch doesn't match.",showArgs:["path"]}}});var gh,hh=h(()=>{"use strict";c();gh={type:"object",properties:{path:{type:"string",description:"Path to the file to apply the patch against for preview."},patch:{type:"string",description:"Unified diff string to preview."}},required:["path","patch"]}});import*as yh from"diff";import{promises as qT}from"fs";var Mr,bh=h(()=>{"use strict";c();hh();Mr={name:"diff.preview",displayName:"Preview Diff",description:"Preview the result of applying a patch to a file without modifying it.",category:"diff",parameters:gh,execute:async n=>{let e=n.path,t=n.patch;try{let o=await qT.readFile(e,"utf8"),r=yh.applyPatch(o,t);return r===!1?"Patch preview failed. The patch would not apply cleanly.":`Preview of ${e} after patch:
|
|
117
189
|
|
|
118
|
-
${
|
|
190
|
+
${r}`}catch(o){return`Error previewing patch: ${o instanceof Error?o.message:String(o)}`}}}});var Th={};re(Th,{diffApplyTool:()=>Dr,diffCreateTool:()=>Er,diffPreviewTool:()=>Mr,diffToolsProject:()=>wh});var wh,Hs=h(()=>{"use strict";c();ch();fh();bh();wh={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:[Er,Dr,Mr],dependencies:{diff:"^7.0.0"}}});var xh,vh=h(()=>{"use strict";c();xh={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 Ae,Nr=h(()=>{"use strict";c();Ae=class{connectionString;constructor(e){this.connectionString=e}}});import Ch from"better-sqlite3";import*as Ks from"fs";var So,Ph=h(()=>{"use strict";c();Nr();So=class extends Ae{getDb(){if(!Ks.existsSync(this.connectionString))throw new Error(`Database file not found: ${this.connectionString}`);return new Ch(this.connectionString,{readonly:!1})}async query(e,t=[]){let o=this.getDb();try{let r=o.prepare(e);return r.reader?r.all(t):(r.run(t),[])}finally{o.close()}}async execute(e,t=[]){let o=this.getDb();try{let s=o.prepare(e).run(t);return{changes:s.changes,lastInsertRowid:s.lastInsertRowid,raw:s}}finally{o.close()}}async getTables(){return(await this.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`PRAGMA table_info("${e}")`):await this.query("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")}static executeSession(e,t,o=[]){if(!Ks.existsSync(e))throw new Error(`Database file not found: ${e}`);let r=new Ch(e,{readonly:!1});try{let s=r.prepare(t);return s.reader?s.all(o):s.run(o)}finally{r.close()}}}});import WT from"pg";var Ar,Sh=h(()=>{"use strict";c();Nr();Ar=class extends Ae{async getClient(){let e=new WT.Client({connectionString:this.connectionString});return await e.connect(),e}convertSql(e){let t=1;return e.replace(/\?/g,()=>`$${t++}`)}async query(e,t=[]){let o=await this.getClient();try{let r=this.convertSql(e);return(await o.query(r,t)).rows}finally{await o.end()}}async execute(e,t=[]){let o=await this.getClient();try{let r=this.convertSql(e),s=await o.query(r,t);return{changes:s.rowCount??0,raw:s}}finally{await o.end()}}async getTables(){return(await this.query("SELECT tablename as name FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema'")).map(o=>o.name)}async getSchema(e){return e?await this.query(`
|
|
119
191
|
SELECT column_name, data_type, is_nullable, column_default
|
|
120
192
|
FROM information_schema.columns
|
|
121
193
|
WHERE table_name = $1
|
|
@@ -123,23 +195,99 @@ ${o}`}catch(r){return`Error previewing patch: ${r instanceof Error?r.message:Str
|
|
|
123
195
|
SELECT table_name as name, table_type
|
|
124
196
|
FROM information_schema.tables
|
|
125
197
|
WHERE table_schema = 'public'
|
|
126
|
-
`)}}});import Jy from"mysql2/promise";var nr,Yu=g(()=>{"use strict";l();or();nr=class extends Pe{async getConnection(){return await Jy.createConnection(this.connectionString)}async query(e,t=[]){let r=await this.getConnection();try{let[o]=await r.execute(e,t);return o}finally{await r.end()}}async execute(e,t=[]){let r=await this.getConnection();try{let[o]=await r.execute(e,t);return{changes:o.affectedRows,lastInsertRowid:o.insertId,raw:o}}finally{await r.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let r=Object.keys(t[0]);return t.map(o=>o[r[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[r]=await t.query("DESCRIBE ??",[e]);return r}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var G,Ce=g(()=>{"use strict";l();Ku();Qu();Yu();G=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new rr(e):e.startsWith("mysql://")?new nr(e):e.startsWith("sqlite://")?new Yt(e.replace("sqlite://","")):new Yt(e)}}});var sr,Vu=g(()=>{"use strict";l();Hu();Ce();k();sr={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:Ju,execute:async s=>{let e=s.db,t=s.sql,r=s.params||[];y(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${r.length}`);try{let n=await G.getAdapter(e).query(t,r);return JSON.stringify(n,null,2)}catch(o){return`Database query error: ${o instanceof Error?o.message:String(o)}`}}}});var Xu,Zu=g(()=>{"use strict";l();Xu={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var ir,ef=g(()=>{"use strict";l();Zu();Ce();ir={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:Xu,execute:async s=>{let e=s.db,t=s.table;try{let o=await G.getAdapter(e).getSchema(t);return JSON.stringify(o,null,2)}catch(r){return`Database schema error: ${r instanceof Error?r.message:String(r)}`}}}});var tf,of=g(()=>{"use strict";l();tf={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var ar,rf=g(()=>{"use strict";l();of();Ce();ar={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:tf,execute:async s=>{let e=s.db;try{let r=await G.getAdapter(e).getTables();return JSON.stringify(r,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var nf,sf=g(()=>{"use strict";l();nf={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to insert into"},data:{type:"object",description:"Key-value pairs of column names and values to insert"}},required:["db","table","data"]}});var lr,af=g(()=>{"use strict";l();sf();Ce();lr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:nf,execute:async s=>{let e=s.db,t=s.table,r=s.data;if(Object.keys(r).length===0)return"Error: No data provided to insert.";try{let o=Object.keys(r).join(", "),n=Object.keys(r).map(()=>"?").join(", "),a=Object.values(r),i=`INSERT INTO ${t} (${o}) VALUES (${n})`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(o){return`Database insert error: ${o instanceof Error?o.message:String(o)}`}}}});var lf,cf=g(()=>{"use strict";l();lf={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to update"},data:{type:"object",description:"Key-value pairs of column names and new values"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","data","where"]}});var cr,pf=g(()=>{"use strict";l();cf();Ce();cr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:lf,execute:async s=>{let e=s.db,t=s.table,r=s.data,o=s.where;if(Object.keys(r).length===0)return"Error: No data provided to update.";try{let n=Object.keys(r).map(m=>`${m} = ?`).join(", "),a=Object.values(r),i=`UPDATE ${t} SET ${n} WHERE ${o}`,p=await G.getAdapter(e).execute(i,a);return JSON.stringify(p,null,2)}catch(n){return`Database update error: ${n instanceof Error?n.message:String(n)}`}}}});var mf,df=g(()=>{"use strict";l();mf={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to delete from"},where:{type:"string",description:'WHERE clause condition (e.g. "id = 5"). DO NOT INCLUDE the word WHERE.'}},required:["db","table","where"]}});var pr,uf=g(()=>{"use strict";l();df();Ce();pr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:mf,execute:async s=>{let e=s.db,t=s.table,r=s.where;try{let o=`DELETE FROM ${t} WHERE ${r}`,a=await G.getAdapter(e).execute(o);return JSON.stringify(a,null,2)}catch(o){return`Database delete error: ${o instanceof Error?o.message:String(o)}`}}}});var ff,gf=g(()=>{"use strict";l();ff={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to count rows from"},where:{type:"string",description:"Optional WHERE clause condition"}},required:["db","table"]}});var mr,hf=g(()=>{"use strict";l();gf();Ce();mr={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:ff,execute:async s=>{let e=s.db,t=s.table,r=s.where;try{let o=r?`WHERE ${r}`:"",n=`SELECT COUNT(*) as count FROM ${t} ${o}`,i=await G.getAdapter(e).query(n);return Array.isArray(i)&&i.length>0?`Rows: ${i[0].count}`:"Count: 0"}catch(o){return`Database count error: ${o instanceof Error?o.message:String(o)}`}}}});var wf={};re(wf,{dbCountTool:()=>mr,dbDeleteTool:()=>pr,dbInsertTool:()=>lr,dbQueryTool:()=>sr,dbSchemaTool:()=>ir,dbTablesTool:()=>ar,dbToolsProject:()=>yf,dbUpdateTool:()=>cr});var yf,Xn=g(()=>{"use strict";l();Vu();ef();rf();af();pf();uf();hf();yf={manifest:{key:"db",name:"db-tools",displayName:"Database Tools",version:"1.0.0",description:"Stateless database operations enabling the AI to interact with local databases.",author:"Sajeer",tools:["db.query","db.schema","db.tables","db.insert","db.update","db.delete","db.count"],category:"database"},tools:[sr,ir,ar,lr,cr,pr,mr],dependencies:{"better-sqlite3":"^11.3.0"}}});var bf,xf=g(()=>{"use strict";l();bf={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});import{NetlifyAPI as Hy}from"netlify";var ve,dr=g(()=>{"use strict";l();ve=class{static getClient(){let e=process.env.NETLIFY_AUTH_TOKEN;if(!e)throw new Error("NETLIFY_AUTH_TOKEN environment variable is required to use Netlify cloud tools.");return new Hy(e)}}});var ur,Tf=g(()=>{"use strict";l();xf();dr();k();ur={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:bf,execute:async s=>{let e=s.siteId,t=s.dir,r=s.message;y(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${r??"none"}"`);try{let n=await ve.getClient().deploy(e,t,{message:r||"Deployed via Toolpack SDK",draft:!1});return JSON.stringify({id:n.deployId,url:n.deploy.url,admin_url:n.deploy.admin_url,state:n.deploy.state},null,2)}catch(o){return`Cloud deployment error: ${o instanceof Error?o.message:String(o)}`}}}});var Pf,Cf=g(()=>{"use strict";l();Pf={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 fr,vf=g(()=>{"use strict";l();Cf();dr();fr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:Pf,execute:async s=>{let e=s.siteId,t=s.deployId;try{let o=await ve.getClient().getSiteDeploy({site_id:e,deploy_id:t});return JSON.stringify({id:o.id,state:o.state,error_message:o.error_message,created_at:o.created_at,updated_at:o.updated_at,url:o.url},null,2)}catch(r){return`Cloud status error: ${r instanceof Error?r.message:String(r)}`}}}});var Sf,$f=g(()=>{"use strict";l();Sf={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 gr,_f=g(()=>{"use strict";l();$f();dr();k();gr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:Sf,execute:async s=>{let e=s.siteId,t=s.limit||5;y(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let o=await ve.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(o))return"Unexpected response format from Netlify API";let n=o.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(n,null,2)}catch(r){return`Cloud list error: ${r instanceof Error?r.message:String(r)}`}}}});var Rf={};re(Rf,{cloudDeployTool:()=>ur,cloudListTool:()=>gr,cloudStatusTool:()=>fr,cloudToolsProject:()=>kf});var kf,Zn=g(()=>{"use strict";l();Tf();vf();_f();kf={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:[ur,fr,gr],dependencies:{netlify:"^13.1.20"}}});l();ce();l();ce();import{EventEmitter as sg}from"events";l();l();l();var je={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 r=this.createDocument(t);this.documents.push(r);let o=new Set(r.tokens);for(let n of o)this.docFrequencies.set(n,(this.docFrequencies.get(n)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let r=t?.limit??5,o=t?.category,n=t?.minScore??0,a=this.tokenize(e.toLowerCase());if(a.length===0)return[];let i=[];for(let c of this.documents){if(o&&c.tool.category!==o)continue;let p=this.computeBM25Score(a,c);p>n&&i.push({toolName:c.toolName,score:p,tool:c.tool})}return i.sort((c,p)=>p.score-c.score).slice(0,r).map(({toolName:c,score:p,tool:m})=>({toolName:c,score:p,tool:this.toSchema(m)}))}getIndexedCount(){return this.documents.length}isIndexed(e){return this.documents.some(t=>t.toolName===e)}createDocument(e){let t=[];for(let a=0;a<je.name;a++)t.push(e.name);for(let a=0;a<je.displayName;a++)t.push(e.displayName);for(let a=0;a<je.description;a++)t.push(e.description);for(let a=0;a<je.category;a++)t.push(e.category);if(e.parameters?.properties)for(let[a,i]of Object.entries(e.parameters.properties)){for(let c=0;c<je.parameterNames;c++)t.push(a);if(i.description)for(let c=0;c<je.parameterDescriptions;c++)t.push(i.description)}let r=t.join(" ").toLowerCase(),o=this.tokenize(r),n=this.computeTermFrequencies(o);return{toolName:e.name,tool:e,text:r,tokens:o,length:o.length,termFrequencies:n}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!Zf.has(t))}computeTermFrequencies(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let r=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,r)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,r)=>t+r.length,0)/this.documents.length}computeBM25Score(e,t){let r=0;for(let o of e){let n=t.termFrequencies.get(o)||0;if(n===0)continue;let a=this.idf.get(o)||0,i=t.length,c=n*(this.k1+1),p=n+this.k1*(1-this.b+this.b*(i/this.avgDocLength));r+=a*(c/p)}return r}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},Zf=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there"]);l();var Fe=class s{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let r of t)this.discoveredTools.add(r);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 s;for(let r of e)if(r.role==="tool"){let o=r;if(typeof o.content=="string")try{let n=JSON.parse(o.content);if(n.query&&n.tools&&Array.isArray(n.tools)){let a=n.tools.map(i=>typeof i=="string"?i:i.name).filter(Boolean);a.length>0&&t.recordDiscovery(n.query,a)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}};l();var tt="tool.search",Le={name:tt,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
|
|
198
|
+
`)}}});import UT from"mysql2/promise";var Or,kh=h(()=>{"use strict";c();Nr();Or=class extends Ae{async getConnection(){return await UT.createConnection(this.connectionString)}async query(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return r}finally{await o.end()}}async execute(e,t=[]){let o=await this.getConnection();try{let[r]=await o.execute(e,t);return{changes:r.affectedRows,lastInsertRowid:r.insertId,raw:r}}finally{await o.end()}}async getTables(){let t=await this.query("SHOW TABLES");if(!t||t.length===0)return[];let o=Object.keys(t[0]);return t.map(r=>r[o[0]])}async getSchema(e){if(e){let t=await this.getConnection();try{let[o]=await t.query("DESCRIBE ??",[e]);return o}finally{await t.end()}}else return await this.query("SHOW TABLES")}}});var J,Oe=h(()=>{"use strict";c();Ph();Sh();kh();J=class{static getAdapter(e){return e.startsWith("postgres://")||e.startsWith("postgresql://")?new Ar(e):e.startsWith("mysql://")?new Or(e):e.startsWith("sqlite://")?new So(e.replace("sqlite://","")):new So(e)}}});var Ir,Rh=h(()=>{"use strict";c();vh();Oe();P();Ir={name:"db.query",displayName:"Database Query",description:"Execute raw SQL queries against an SQLite, PostgreSQL, or MySQL database.",category:"database",parameters:xh,execute:async n=>{let e=n.db,t=n.sql,o=n.params||[];y(`[db.query] execute db="${e}" sql="${t.substring(0,80)}..." params=${o.length}`);try{let s=await J.getAdapter(e).query(t,o);return JSON.stringify(s,null,2)}catch(r){return`Database query error: ${r instanceof Error?r.message:String(r)}`}}}});var $h,_h=h(()=>{"use strict";c();$h={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Optional specific table name to inspect. If omitted, returns structural summary of all tables."}},required:["db"]}});var Lr,Eh=h(()=>{"use strict";c();_h();Oe();Lr={name:"db.schema",displayName:"Database Schema",description:"Get the structural schema of a database or a specific table.",category:"database",parameters:$h,execute:async n=>{let e=n.db,t=n.table;try{let r=await J.getAdapter(e).getSchema(t);return JSON.stringify(r,null,2)}catch(o){return`Database schema error: ${o instanceof Error?o.message:String(o)}`}}}});var Dh,Mh=h(()=>{"use strict";c();Dh={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"}},required:["db"]}});var jr,Nh=h(()=>{"use strict";c();Mh();Oe();jr={name:"db.tables",displayName:"Database Tables",description:"List all user tables in the database.",category:"database",parameters:Dh,execute:async n=>{let e=n.db;try{let o=await J.getAdapter(e).getTables();return JSON.stringify(o,null,2)}catch(t){return`Database tables error: ${t instanceof Error?t.message:String(t)}`}}}});var Ah,Oh=h(()=>{"use strict";c();Ah={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 Fr,Ih=h(()=>{"use strict";c();Oh();Oe();Fr={name:"db.insert",displayName:"Database Insert",description:"Insert a new row into an SQLite table safely.",category:"database",parameters:Ah,execute:async n=>{let e=n.db,t=n.table,o=n.data;if(Object.keys(o).length===0)return"Error: No data provided to insert.";try{let r=Object.keys(o).join(", "),s=Object.keys(o).map(()=>"?").join(", "),i=Object.values(o),a=`INSERT INTO ${t} (${r}) VALUES (${s})`,p=await J.getAdapter(e).execute(a,i);return JSON.stringify(p,null,2)}catch(r){return`Database insert error: ${r instanceof Error?r.message:String(r)}`}},confirmation:{level:"medium",reason:"This will insert rows into the database, creating permanent records.",showArgs:["table","data"]}}});var Lh,jh=h(()=>{"use strict";c();Lh={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 qr,Fh=h(()=>{"use strict";c();jh();Oe();qr={name:"db.update",displayName:"Database Update",description:"Update existing rows in a database table.",category:"database",parameters:Lh,execute:async n=>{let e=n.db,t=n.table,o=n.data,r=n.where;if(Object.keys(o).length===0)return"Error: No data provided to update.";try{let s=Object.keys(o).map(m=>`${m} = ?`).join(", "),i=Object.values(o),a=`UPDATE ${t} SET ${s} WHERE ${r}`,p=await J.getAdapter(e).execute(a,i);return JSON.stringify(p,null,2)}catch(s){return`Database update error: ${s instanceof Error?s.message:String(s)}`}},confirmation:{level:"high",reason:"This will update database rows, potentially affecting multiple records.",showArgs:["table","data","where"]}}});var qh,Wh=h(()=>{"use strict";c();qh={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 Wr,Uh=h(()=>{"use strict";c();Wh();Oe();Wr={name:"db.delete",displayName:"Database Delete",description:"Delete rows from a database table.",category:"database",parameters:qh,execute:async n=>{let e=n.db,t=n.table,o=n.where;try{let r=`DELETE FROM ${t} WHERE ${o}`,i=await J.getAdapter(e).execute(r);return JSON.stringify(i,null,2)}catch(r){return`Database delete error: ${r instanceof Error?r.message:String(r)}`}},confirmation:{level:"high",reason:"This will permanently delete rows from the database.",showArgs:["table","where"]}}});var Gh,Bh=h(()=>{"use strict";c();Gh={type:"object",properties:{db:{type:"string",description:"Database connection URI or SQLite file path"},table:{type:"string",description:"Name of the table to count rows from"},where:{type:"string",description:"Optional WHERE clause condition"}},required:["db","table"]}});var Ur,zh=h(()=>{"use strict";c();Bh();Oe();Ur={name:"db.count",displayName:"Database Count",description:"Count rows in a database table.",category:"database",parameters:Gh,execute:async n=>{let e=n.db,t=n.table,o=n.where;try{let r=o?`WHERE ${o}`:"",s=`SELECT COUNT(*) as count FROM ${t} ${r}`,a=await J.getAdapter(e).query(s);return Array.isArray(a)&&a.length>0?`Rows: ${a[0].count}`:"Count: 0"}catch(r){return`Database count error: ${r instanceof Error?r.message:String(r)}`}}}});var Kh={};re(Kh,{dbCountTool:()=>Ur,dbDeleteTool:()=>Wr,dbInsertTool:()=>Fr,dbQueryTool:()=>Ir,dbSchemaTool:()=>Lr,dbTablesTool:()=>jr,dbToolsProject:()=>Hh,dbUpdateTool:()=>qr});var Hh,Js=h(()=>{"use strict";c();Rh();Eh();Nh();Ih();Fh();Uh();zh();Hh={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:[Ir,Lr,jr,Fr,qr,Wr,Ur],dependencies:{"better-sqlite3":"^11.3.0"}}});var Jh,Qh=h(()=>{"use strict";c();Jh={type:"object",properties:{siteId:{type:"string",description:'The Netlify Site ID to deploy to (e.g. "api_id" from Netlify UI)'},dir:{type:"string",description:'The local directory path to deploy (e.g. "./dist" or "./public")'},message:{type:"string",description:"Optional deployment message/commit note"}},required:["siteId","dir"]}});import{NetlifyAPI as GT}from"netlify";var Ie,Gr=h(()=>{"use strict";c();Ie=class{static getClient(){let e=process.env.NETLIFY_AUTH_TOKEN;if(!e)throw new Error("NETLIFY_AUTH_TOKEN environment variable is required to use Netlify cloud tools.");return new GT(e)}}});var Br,Vh=h(()=>{"use strict";c();Qh();Gr();P();Br={name:"cloud.deploy",displayName:"Cloud Deploy",description:"Deploy a static directory to Netlify.",category:"cloud",parameters:Jh,execute:async n=>{let e=n.siteId,t=n.dir,o=n.message;y(`[cloud.deploy] execute siteId="${e}" dir="${t}" message="${o??"none"}"`);try{let s=await Ie.getClient().deploy(e,t,{message:o||"Deployed via Toolpack SDK",draft:!1});return JSON.stringify({id:s.deployId,url:s.deploy.url,admin_url:s.deploy.admin_url,state:s.deploy.state},null,2)}catch(r){return`Cloud deployment error: ${r instanceof Error?r.message:String(r)}`}},confirmation:{level:"high",reason:"This will deploy to production (live site).",showArgs:["siteId","dir"]}}});var Xh,Yh=h(()=>{"use strict";c();Xh={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 zr,Zh=h(()=>{"use strict";c();Yh();Gr();zr={name:"cloud.status",displayName:"Cloud Status",description:"Check the status of a specific Netlify deployment.",category:"cloud",parameters:Xh,execute:async n=>{let e=n.siteId,t=n.deployId;try{let r=await Ie.getClient().getSiteDeploy({site_id:e,deploy_id:t});return JSON.stringify({id:r.id,state:r.state,error_message:r.error_message,created_at:r.created_at,updated_at:r.updated_at,url:r.url},null,2)}catch(o){return`Cloud status error: ${o instanceof Error?o.message:String(o)}`}}}});var ey,ty=h(()=>{"use strict";c();ey={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 Hr,oy=h(()=>{"use strict";c();ty();Gr();P();Hr={name:"cloud.list",displayName:"Cloud Deployments List",description:"List recent deployments for a Netlify site.",category:"cloud",parameters:ey,execute:async n=>{let e=n.siteId,t=n.limit||5;y(`[cloud.list] execute siteId="${e}" limit=${t}`);try{let r=await Ie.getClient().listSiteDeploys({site_id:e,page:1,per_page:t});if(!Array.isArray(r))return"Unexpected response format from Netlify API";let s=r.map(i=>({id:i.id,state:i.state,created_at:i.created_at,url:i.url,branch:i.branch,title:i.title}));return JSON.stringify(s,null,2)}catch(o){return`Cloud list error: ${o instanceof Error?o.message:String(o)}`}}}});var ny={};re(ny,{cloudDeployTool:()=>Br,cloudListTool:()=>Hr,cloudStatusTool:()=>zr,cloudToolsProject:()=>ry});var ry,Qs=h(()=>{"use strict";c();Vh();Zh();oy();ry={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:[Br,zr,Hr],dependencies:{netlify:"^13.1.20"}}});c();ne();c();ne();import{EventEmitter as Hy}from"events";c();ne();var ht=class extends A{constructor(t,o,r,s,i,a){super(t,"CONTEXT_WINDOW_EXCEEDED",400,a);this.conversationId=o;this.currentTokens=r;this.contextWindowLimit=s;this.strategy=i;this.name="ContextWindowExceededError"}conversationId;currentTokens;contextWindowLimit;strategy;getOverageTokens(){return Math.max(0,this.currentTokens-this.contextWindowLimit)}getUsagePercentage(){return Math.round(this.currentTokens/this.contextWindowLimit*100)}getDetailedReport(){return`
|
|
199
|
+
Context Window Exceeded
|
|
200
|
+
=======================
|
|
201
|
+
Conversation ID: ${this.conversationId}
|
|
202
|
+
Current Tokens: ${this.currentTokens}
|
|
203
|
+
Context Window Limit: ${this.contextWindowLimit}
|
|
204
|
+
Overage: ${this.getOverageTokens()} tokens
|
|
205
|
+
Usage: ${this.getUsagePercentage()}%
|
|
206
|
+
Strategy: ${this.strategy}
|
|
207
|
+
|
|
208
|
+
Message: ${this.message}
|
|
209
|
+
`.trim()}};var yt=class extends A{constructor(t,o,r,s,i,a){super(t,"SUMMARIZATION_ERROR",500,a);this.conversationId=o;this.messageCount=r;this.failureReason=s;this.summaryAttempt=i;this.name="SummarizationError"}conversationId;messageCount;failureReason;summaryAttempt;isRetryable(){return this.failureReason==="provider_error"||this.failureReason==="insufficient_tokens"}getSuggestedRecovery(){switch(this.failureReason){case"provider_error":return"Retry the summarization request or switch to a different summarizer model";case"invalid_response":return"Review the summarizer prompt or use a different model";case"insufficient_tokens":return"Reduce the number of messages to summarize or increase the summary token budget";case"invalid_quality":return"Adjust summarization parameters or use a more capable model";default:return"Manual intervention required"}}getDetailedReport(){let t=`
|
|
210
|
+
Summarization Error
|
|
211
|
+
===================
|
|
212
|
+
Conversation ID: ${this.conversationId}
|
|
213
|
+
Messages Attempted: ${this.messageCount}
|
|
214
|
+
Failure Reason: ${this.failureReason}
|
|
215
|
+
Retryable: ${this.isRetryable()?"Yes":"No"}
|
|
216
|
+
Recovery Action: ${this.getSuggestedRecovery()}
|
|
217
|
+
|
|
218
|
+
Message: ${this.message}`;return this.summaryAttempt?t+`
|
|
219
|
+
|
|
220
|
+
Partial Summary:
|
|
221
|
+
${this.summaryAttempt.substring(0,500)}${this.summaryAttempt.length>500?"...":""}`:t.trim()}};c();var nn=null;async function Ey(){if(!nn)try{nn=await import("js-tiktoken")}catch{}return nn}var Ti={"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},Dy=2;async function My(n,e){try{let t=await Ey();if(!t)return Re(n);let o=t.encoding_for_model(e),r=0,s=Ti[e]??Ti.__default__;for(let i of n){if(r+=s,typeof i.content=="string")r+=o.encode(i.content).length;else if(Array.isArray(i.content))for(let a of i.content)a.type==="text"?r+=o.encode(a.text).length:(a.type==="image_data"||a.type==="image_url"||a.type==="image_file")&&(r+=256);if(i.tool_calls?.length)for(let a of i.tool_calls)r+=o.encode(a.function.name).length,r+=o.encode(a.function.arguments).length;i.name&&(r+=o.encode(i.name).length)}return r+=Dy,r}catch{return Re(n)}}async function Ny(n,e){try{let t=Re(n);return Math.ceil(t*1.1)}catch{return Re(n)}}async function Ay(n,e){try{let t=Re(n);return Math.ceil(t*1.05)}catch{return Re(n)}}async function Oy(n,e){let t=Re(n);return Math.ceil(t*1.05)}function Re(n){let e=0;for(let t of n){if(e+=50,typeof t.content=="string")e+=t.content.length;else if(Array.isArray(t.content))for(let o of t.content)o.type==="text"?e+=o.text.length:(o.type==="image_data"||o.type==="image_url"||o.type==="image_file")&&(e+=1e3);if(t.tool_calls?.length)for(let o of t.tool_calls)e+=o.function.name.length,e+=o.function.arguments.length;t.name&&(e+=t.name.length)}return Math.ceil(e/4)}async function xi(n,e,t){let o=t.toLowerCase();return o==="openai"||o==="openai-gpt"?My(n,e):o==="anthropic"||o==="claude"?Ny(n,e):o==="gemini"||o==="google"?Ay(n,e):o==="ollama"?Oy(n,e):Re(n)}function Tx(n,e,t){let o=e-t;return n>o}function xx(n,e){return Math.round(n/e*100)}function vi(n,e=1.15){return Math.ceil(n*e)}c();function Ci(n,e,t=!0){let o=n.length,r=[],s=0,i=[];n.forEach((p,m)=>{t&&p.role==="system"||p.role!=="tool"&&i.push({index:m,message:p})});for(let{message:p}of i){if(s>=e)break;let m=sn(p);if(s+=m,r.push(p),p.role==="assistant"&&p.tool_calls?.length){let d=new Set(p.tool_calls.map(g=>g.id));for(let g of n)g.role==="tool"&&g.tool_call_id&&d.has(g.tool_call_id)&&(s+=sn(g),r.push(g))}}let a=new Set(r),l=n.filter(p=>!a.has(p));return{removed:r.length,tokensReclaimed:s,newTotal:l.length,pruneInfo:{beforeCount:o,afterCount:l.length,removedMessages:r}}}function Px(n,e){if(typeof n.content=="string"){let t=e*4;if(n.content.length<=t)return n;let o=n.content.substring(0,t),r=Math.ceil((n.content.length-t)/4);return{...n,content:`${o}
|
|
222
|
+
|
|
223
|
+
[...truncated ${r} tokens]`}}else if(Array.isArray(n.content)){let t=n.content.filter(a=>a.type==="text"),o=t.reduce((a,l)=>a+(l.text?.length||0),0),r=e*4;if(o<=r)return n;let s=0,i=[];for(let a of t)if(a.type==="text"){let l=r-s;if(l<=0)break;let p=a.text;if(p.length<=l)i.push(a),s+=p.length;else{let m=p.substring(0,l),d=Math.ceil((p.length-l)/4);i.push({type:"text",text:`${m}
|
|
224
|
+
|
|
225
|
+
[...truncated ${d} tokens]`});break}}return{...n,content:i.length>0?i:n.content}}return n}function sn(n){let e=4;if(typeof n.content=="string")e+=Math.ceil(n.content.length/4);else if(Array.isArray(n.content))for(let t of n.content)t.type==="text"?e+=Math.ceil((t.text?.length||0)/4):(t.type==="image_data"||t.type==="image_url"||t.type==="image_file")&&(e+=256);if(n.tool_calls?.length)for(let t of n.tool_calls)e+=Math.ceil(t.function.name.length/4),e+=Math.ceil(t.function.arguments.length/4);return n.name&&(e+=Math.ceil(n.name.length/4)),e}function Sx(n){let e={system:[],user:[],assistant:[],tool:[]};return n.forEach(t=>{e[t.role]??=[],e[t.role].push(t)}),e}function kx(n){let e=0,t={},o=0;for(let r of n){let s=sn(r);e+=s,o=Math.max(o,s),t[r.role]??=0,t[r.role]++}return{totalMessages:n.length,totalTokens:e,byRole:t,largestMessageTokens:o}}c();ne();function an(n){return n.content==null?"":typeof n.content=="string"?n.content:n.content.map(e=>e.type==="text"?e.text:e.type==="image_url"?`[image: ${e.image_url.url}]`:e.type==="image_file"?`[image-file: ${e.image_file.path}]`:e.type==="image_data"?`[image-data: ${e.image_data.mimeType}]`:"").filter(Boolean).join(" ")}function Iy(n,e){if(e)return e;let t=n.filter(l=>l.role==="user"),o=n.filter(l=>l.role==="assistant"),r=n.filter(l=>l.role==="tool"),s=n.length,i=t.length,a=o.length;return`Please provide a concise summary of the following conversation history. The conversation contains ${s} messages (${i} user messages, ${a} assistant responses${r.length>0?`, and ${r.length} tool responses`:""}).
|
|
226
|
+
|
|
227
|
+
Focus on:
|
|
228
|
+
1. Key topics discussed
|
|
229
|
+
2. Important decisions or conclusions
|
|
230
|
+
3. User's intent and goals
|
|
231
|
+
4. Relevant context for continuing the conversation
|
|
232
|
+
|
|
233
|
+
The summary should be comprehensive yet concise, preserving all critical information needed to continue the conversation naturally.
|
|
234
|
+
|
|
235
|
+
---
|
|
236
|
+
CONVERSATION:
|
|
237
|
+
${n.map((l,p)=>{let m=an(l);return`[Message ${p+1}] ${l.role.toUpperCase()}: ${m.substring(0,200)}${m.length>200?"...":""}`}).join(`
|
|
238
|
+
`)}
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
SUMMARY:`}function ln(n,e){return{role:"system",content:`[Context Summary]
|
|
242
|
+
This conversation has been summarized to manage context window. The following is a summary of the first ${e} messages:
|
|
243
|
+
|
|
244
|
+
${n}
|
|
245
|
+
|
|
246
|
+
[End Summary]
|
|
247
|
+
|
|
248
|
+
Use this summary to understand the conversation context. When responding, acknowledge that you're aware of the previous conversation and continue naturally.`}}function Ex(n){let e=new Set,t=[],o=[],r="";for(let s of n)if(s.role==="user"){let i=an(s);r=i,i.includes("?")&&o.push(i.split(`
|
|
249
|
+
`)[0]);let a=i.match(/\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b/g);a&&a.forEach(l=>e.add(l))}else if(s.role==="assistant"){let i=an(s);if(i.includes("decided")||i.includes("concluded")||i.includes("determined")){let a=i.split(/[.!?]+/);for(let l of a)(l.includes("decided")||l.includes("concluded")||l.includes("determined"))&&t.push(l.trim())}}return{topics:Array.from(e).slice(0,10),decisions:t.slice(0,5),userGoals:o.slice(0,5),context:r.substring(0,200)}}function Ly(n){return Math.ceil(n.length/4)}function Pi(n){let e=[];return(!n.summary||n.summary.length<10)&&e.push("Summary is too short"),n.summary.length>5e3&&e.push("Summary is excessively long"),n.messageCount<2&&e.push("Must summarize at least 2 messages"),n.summaryTokens>=n.originalTokens*.8&&e.push("Summary is not significantly shorter than original messages"),n.tokensSaved<0&&e.push("Token calculation error: saved tokens is negative"),{valid:e.length===0,issues:e}}function Si(n,e){let t=Iy(n,e.summaryPrompt);return[{role:"system",content:`You are a conversation summarizer. Your task is to create a clear, concise summary of the provided conversation that preserves all critical information.
|
|
250
|
+
|
|
251
|
+
Maximum summary length: ${e.maxSummaryTokens||500} tokens.
|
|
252
|
+
Format: Write only the summary without any additional commentary.`},{role:"user",content:t}]}function ki(n,e,t){let o=Ly(n),r=Math.max(0,t-o);return{summary:n.trim(),messageCount:e.length,originalTokens:t,summaryTokens:o,tokensSaved:r,timestamp:new Date}}function Dx(n,e,t){let o=[...n];return o.push(ln(e.summary,e.messageCount)),o.push(...t),o}function Mx(n,e,t){let o=Math.round(n.tokensSaved/n.originalTokens*100);return`
|
|
253
|
+
Summarization Report
|
|
254
|
+
====================
|
|
255
|
+
Timestamp: ${n.timestamp.toISOString()}
|
|
256
|
+
Status: \u2713 Summarization completed
|
|
257
|
+
|
|
258
|
+
Input Analysis:
|
|
259
|
+
- Messages summarized: ${n.messageCount}
|
|
260
|
+
- Original token count: ${n.originalTokens}
|
|
261
|
+
- Summary token count: ${n.summaryTokens}
|
|
262
|
+
- Tokens saved: ${n.tokensSaved} (${o}% reduction)
|
|
263
|
+
|
|
264
|
+
Message Count:
|
|
265
|
+
- Before: ${e} messages
|
|
266
|
+
- After: ${t} messages
|
|
267
|
+
- Reduction: ${e-t} messages
|
|
268
|
+
|
|
269
|
+
Summary Preview:
|
|
270
|
+
${n.summary.substring(0,300)}${n.summary.length>300?"...":""}
|
|
271
|
+
`.trim()}function Nx(n){if(n.length===0)throw new A("Cannot merge empty summarization results","CONTEXT_WINDOW_ERROR");return{summary:n.map(t=>`[Round ${n.indexOf(t)+1}] ${t.summary}`).join(`
|
|
272
|
+
|
|
273
|
+
`),messageCount:n.reduce((t,o)=>t+o.messageCount,0),originalTokens:n.reduce((t,o)=>t+o.originalTokens,0),summaryTokens:n.reduce((t,o)=>t+o.summaryTokens,0),tokensSaved:n.reduce((t,o)=>t+o.tokensSaved,0),timestamp:new Date}}c();var cn=class{states=new Map;config;maxTokens=1e5;constructor(e){this.config=e}getOrCreateState(e){return this.states.has(e)||this.states.set(e,{conversationId:e,estimatedTokens:0,lastUpdated:Date.now(),pruneCount:0,lastPrunedAt:void 0,warningsSent:0,summarizationCount:0}),this.states.get(e)}updateTokenCount(e,t){let o=this.getOrCreateState(e);return o.estimatedTokens=t,o.lastUpdated=Date.now(),o}recordPruneOperation(e,t){let o=this.getOrCreateState(e);return o.pruneCount++,o.lastPrunedAt=Date.now(),o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}recordWarning(e){let t=this.getOrCreateState(e);return t.warningsSent++,t.lastUpdated=Date.now(),t}recordSummarization(e,t){let o=this.getOrCreateState(e);return o.summarizationCount++,o.estimatedTokens=Math.max(0,o.estimatedTokens-t),o.lastUpdated=Date.now(),o}getState(e){return this.states.get(e)}getAllStates(){return Array.from(this.states.values())}deleteState(e){return this.states.delete(e)}clearAllStates(){this.states.clear()}getStatistics(e){let t=this.states.get(e);if(!t)return null;let o=this.config.pruneThreshold||1e5,r=Math.round(t.estimatedTokens/o*100);return{conversationId:e,currentTokens:t.estimatedTokens,pruneCount:t.pruneCount,summarizationCount:t.summarizationCount,warningsSent:t.warningsSent,lastActivity:new Date(t.lastUpdated),contextWindowPercentage:r}}getExceedingThreshold(e){let t=e||this.maxTokens*(this.config.pruneThreshold||85)/100;return Array.from(this.states.values()).filter(o=>o.estimatedTokens>t)}getAtRiskConversations(e=80){let t=this.maxTokens,o=t*e/100;return Array.from(this.states.values()).filter(r=>r.estimatedTokens>o&&r.estimatedTokens<=t)}generateReport(){let e=this.getAllStates();if(e.length===0)return"No conversations tracked yet.";let t=this.config.pruneThreshold||1e5,o=["Context Window State Report","==========================",`Report Generated: ${new Date().toISOString()}`,`Context Window Limit: ${t} tokens`,`Total Conversations: ${e.length}`,""],r=e.reduce((d,g)=>d+g.estimatedTokens,0),s=e.reduce((d,g)=>d+g.pruneCount,0),i=e.reduce((d,g)=>d+g.summarizationCount,0),a=Math.round(r/e.length);o.push("Summary:"),o.push(`- Total tokens across all conversations: ${r}`),o.push(`- Average tokens per conversation: ${a}`),o.push(`- Total prune operations: ${s}`),o.push(`- Total summarizations: ${i}`),o.push("");let l=this.getAtRiskConversations();l.length>0&&(o.push(`At-Risk Conversations (80%+ threshold): ${l.length}`),l.forEach(d=>{let g=Math.round(d.estimatedTokens/t*100);o.push(`- ${d.conversationId}: ${d.estimatedTokens}/${t} tokens (${g}%)`)}),o.push(""));let p=this.getExceedingThreshold();return p.length>0&&(o.push(`Exceeded Conversations: ${p.length}`),p.forEach(d=>{let g=d.estimatedTokens-t;o.push(`- ${d.conversationId}: ${d.estimatedTokens}/${t} tokens (+${g} over)`)}),o.push("")),o.push("Most Active Conversations (by operations):"),[...e].sort((d,g)=>{let w=d.pruneCount+d.summarizationCount;return g.pruneCount+g.summarizationCount-w}).slice(0,5).forEach(d=>{let g=d.pruneCount+d.summarizationCount;o.push(`- ${d.conversationId}: ${d.pruneCount} prunes, ${d.summarizationCount} summarizations (${g} operations)`)}),o.join(`
|
|
274
|
+
`)}export(){let e={};for(let[t,o]of this.states.entries())e[t]={...o,lastUpdated:o.lastUpdated,lastPrunedAt:o.lastPrunedAt};return e}import(e){for(let[t,o]of Object.entries(e))this.states.set(t,{...o,lastUpdated:typeof o.lastUpdated=="number"?o.lastUpdated:new Date(o.lastUpdated).getTime(),lastPrunedAt:o.lastPrunedAt&&typeof o.lastPrunedAt!="number"?new Date(o.lastPrunedAt).getTime():o.lastPrunedAt})}pruneInactiveConversations(e=60){let t=Date.now()-e*60*1e3,o=[];for(let[r,s]of this.states.entries())s.lastUpdated<t&&o.push(r);return o.forEach(r=>this.states.delete(r)),o}getMemoryUsage(){let e=this.states.size,t=e*500;return{conversationCount:e,approximateByteSize:t}}validateIntegrity(){let e=[];for(let[t,o]of this.states.entries())(!t||typeof t!="string")&&e.push(`Invalid conversation ID: ${t}`),o.estimatedTokens<0&&e.push(`Negative token count for ${t}: ${o.estimatedTokens}`),o.pruneCount<0&&e.push(`Negative prune count for ${t}: ${o.pruneCount}`),o.summarizationCount<0&&e.push(`Negative summarization count for ${t}: ${o.summarizationCount}`),o.warningsSent<0&&e.push(`Negative warning count for ${t}: ${o.warningsSent}`),(typeof o.lastUpdated!="number"||o.lastUpdated<=0)&&e.push(`Invalid lastUpdated timestamp for ${t}`),o.lastPrunedAt!==void 0&&(typeof o.lastPrunedAt!="number"||o.lastPrunedAt<=0)&&e.push(`Invalid lastPrunedAt timestamp for ${t}`);return{isValid:e.length===0,issues:e}}};function Ri(n){return new cn(n)}c();c();c();var Ve={name:3,displayName:2.5,description:2,category:1.5,parameterNames:1,parameterDescriptions:.5},bt=class{documents=[];avgDocLength=0;idf=new Map;totalDocs=0;docFrequencies=new Map;k1=1.2;b=.75;index(e){this.documents=[],this.docFrequencies.clear(),this.idf.clear();for(let t of e){let o=this.createDocument(t);this.documents.push(o);let r=new Set(o.tokens);for(let s of r)this.docFrequencies.set(s,(this.docFrequencies.get(s)||0)+1)}this.totalDocs=this.documents.length,this.computeIDF(),this.avgDocLength=this.computeAvgDocLength()}search(e,t){let o=t?.limit??5,r=t?.category,s=t?.minScore??0,i=this.tokenize(e.toLowerCase());if(i.length===0)return[];let a=[];for(let l of this.documents){if(r&&l.tool.category!==r)continue;let p=this.computeBM25Score(i,l);p>s&&a.push({toolName:l.toolName,score:p,tool:l.tool})}return a.sort((l,p)=>p.score-l.score).slice(0,o).map(({toolName:l,score:p,tool:m})=>({toolName:l,score:p,tool:this.toSchema(m)}))}getIndexedCount(){return this.documents.length}isIndexed(e){return this.documents.some(t=>t.toolName===e)}createDocument(e){let t=[];for(let i=0;i<Ve.name;i++)t.push(e.name);for(let i=0;i<Ve.displayName;i++)t.push(e.displayName);for(let i=0;i<Ve.description;i++)t.push(e.description);for(let i=0;i<Ve.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<Ve.parameterNames;l++)t.push(i);if(a.description)for(let l=0;l<Ve.parameterDescriptions;l++)t.push(a.description)}let o=t.join(" ").toLowerCase(),r=this.tokenize(o),s=this.computeTermFrequencies(r);return{toolName:e.name,tool:e,text:o,tokens:r,length:r.length,termFrequencies:s}}tokenize(e){return e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>1).filter(t=>!jy.has(t))}computeTermFrequencies(e){let t=new Map;for(let o of e)t.set(o,(t.get(o)||0)+1);return t}computeIDF(){this.idf.clear();for(let[e,t]of this.docFrequencies){let o=Math.log((this.totalDocs-t+.5)/(t+.5)+1);this.idf.set(e,o)}}computeAvgDocLength(){return this.documents.length===0?0:this.documents.reduce((t,o)=>t+o.length,0)/this.documents.length}computeBM25Score(e,t){let o=0;for(let r of e){let s=t.termFrequencies.get(r)||0;if(s===0)continue;let i=this.idf.get(r)||0,a=t.length,l=s*(this.k1+1),p=s+this.k1*(1-this.b+this.b*(a/this.avgDocLength));o+=i*(l/p)}return o}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}},jy=new Set(["a","an","the","and","or","but","in","on","at","to","for","of","with","by","from","as","is","was","are","were","been","be","have","has","had","do","does","did","will","would","could","should","may","might","must","shall","can","need","it","its","this","that","these","those","i","you","he","she","we","they","what","which","who","whom","when","where","why","how","all","each","every","both","few","more","most","other","some","such","no","nor","not","only","own","same","so","than","too","very","just","also","now","here","there"]);c();var Xe=class n{discoveredTools=new Set;searchHistory=[];recordDiscovery(e,t){for(let o of t)this.discoveredTools.add(o);this.searchHistory.push({query:e,tools:t,timestamp:Date.now()})}getDiscoveredTools(){return Array.from(this.discoveredTools)}isDiscovered(e){return this.discoveredTools.has(e)}getDiscoveredCount(){return this.discoveredTools.size}getSearchHistory(){return[...this.searchHistory]}static fromMessages(e){let t=new n;for(let o of e)if(o.role==="tool"){let r=o;if(typeof r.content=="string")try{let s=JSON.parse(r.content);if(s.query&&s.tools&&Array.isArray(s.tools)){let i=s.tools.map(a=>typeof a=="string"?a:a.name).filter(Boolean);i.length>0&&t.recordDiscovery(s.query,i)}}catch{}}return t}clear(){this.discoveredTools.clear(),this.searchHistory=[]}merge(e){for(let t of e.getDiscoveredTools())this.discoveredTools.add(t);this.searchHistory.push(...e.getSearchHistory())}};c();var wt="tool.search",Ye={name:wt,displayName:"Search Tools",category:"meta",description:`Search for available tools by keyword or natural language query.
|
|
127
275
|
Use this to discover tools before using them.
|
|
128
276
|
Examples: "file operations", "web scraping", "run command", "http request"
|
|
129
277
|
|
|
130
278
|
Returns a list of matching tools with their names, descriptions, and parameters.
|
|
131
|
-
After discovering tools, you can call them directly by name.`,parameters:{type:"object",properties:{query:{type:"string",description:'Natural language search query (e.g., "read files", "web scraping", "execute shell commands")'},category:{type:"string",description:"Optional: filter by category",enum:["filesystem","network","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}};function
|
|
132
|
-
`)}var
|
|
133
|
-
Working directory: ${
|
|
134
|
-
Available tool categories: ${
|
|
279
|
+
After discovering tools, you can call them directly by name.`,parameters:{type:"object",properties:{query:{type:"string",description:'Natural language search query (e.g., "read files", "web scraping", "execute shell commands")'},category:{type:"string",description:"Optional: filter by category",enum:["filesystem","network","execution","system","meta"]}},required:["query"]},execute:async()=>{throw new Error("tool.search execution must be handled by AIClient")}};function Tt(){return{name:Ye.name,displayName:Ye.displayName,description:Ye.description,parameters:Ye.parameters,category:Ye.category}}function Mo(n){return n===wt}c();var Fy={filesystem:"File operations (read, write, delete, list, search files)",network:"HTTP requests and web scraping (GET, POST, fetch pages, extract data)",execution:"Run shell commands and manage processes",system:"System information, environment variables, disk usage",meta:"Tool discovery and management"};function pn(n){let e=n.getCategories();if(e.length===0)return"No tools are currently available.";let t=["You have access to tools in the following categories:",""];for(let o of e){let s=n.getByCategory(o).length,i=Fy[o]||o;t.push(`- **${o}** (${s} tools): ${i}`)}return t.push(""),t.push("Use `tool.search` to discover specific tools when needed."),t.push('Example: tool.search({ query: "read file" }) to find file reading tools.'),t.join(`
|
|
280
|
+
`)}var xt=class{discoveryCache=new Xe;async resolve(e,t,o){return o.enabled?o.toolSearch?.enabled?this.resolveWithToolSearch(e,t,o):this.resolveLegacy(t,o):[]}getDiscoveryCache(){return this.discoveryCache}clearDiscoveryCache(){this.discoveryCache.clear()}resolveWithToolSearch(e,t,o){let r=[],s=new Set;r.push(Tt()),s.add(wt);let i=o.toolSearch?.alwaysLoadedTools??[];for(let l of i){let p=t.get(l);p&&!s.has(l)&&(r.push(this.toSchema(p)),s.add(l))}let a=o.toolSearch?.alwaysLoadedCategories??[];for(let l of a)for(let p of t.getByCategory(l))s.has(p.name)||(r.push(this.toSchema(p)),s.add(p.name));if(o.toolSearch?.cacheDiscoveredTools!==!1){let l=Xe.fromMessages(e);this.discoveryCache.merge(l);let p=this.discoveryCache.getDiscoveredTools();for(let m of p){let d=t.get(m);d&&!s.has(m)&&d.cacheable!==!1&&(r.push(this.toSchema(d)),s.add(m))}}return r}resolveLegacy(e,t){let o;if(t.enabledTools.length===0&&t.enabledToolCategories.length===0)o=e.getEnabled();else{let r=e.getByNames(t.enabledTools),s=e.getByCategories(t.enabledToolCategories),i=new Set;o=[];for(let a of[...r,...s])i.has(a.name)||(i.add(a.name),o.push(a))}return o.map(r=>this.toSchema(r))}toSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category}}};vt();c();function $i(n){if(n.disabled)return"";let e=n.includeWorkingDirectory!==!1,t=n.includeToolCategories!==!1,o=e?`
|
|
281
|
+
Working directory: ${n.workingDirectory}`:"",r=t&&n.toolCategories.length>0?`
|
|
282
|
+
Available tool categories: ${n.toolCategories.join(", ")}`:"";return`You are an AI assistant with access to tools that let you interact with the user's system.${o}${r}
|
|
135
283
|
|
|
136
284
|
When the user asks you to do something, be proactive:
|
|
137
285
|
- Use your tools to find information rather than asking the user for details you can discover yourself
|
|
138
286
|
- Read files, list directories, and explore the codebase when asked to analyze or understand a project
|
|
139
|
-
- Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}
|
|
140
|
-
`):""}return""}
|
|
287
|
+
- Only ask the user for clarification when you genuinely cannot determine their intent or lack the required tools`}c();var Ze=class{analyticalPatterns=[/\b(analyze|find|search|check|list|show)\b/i,/\b(biggest|largest|smallest|most|least|all|every|count)\b/i,/\b(explain|understand|review|audit|inspect|examine)\b/i,/\b(compare|difference|similar|match|pattern)\b/i,/\b(what|where|how many|which|who|when|why|how)\b/i,/\?$/];actionPatterns=[/\b(create|write|update|modify|edit|patch|delete|remove|rename|move|copy)\b/i,/\b(run|execute|start|stop|restart|deploy|install|build)\b/i,/\b(fix|refactor|implement|add|change|replace|insert)\b/i,/\b(make|do|set|configure|setup|initialize)\b/i];classify(e){if(!e||e.trim().length===0)return{type:"conversational",confidence:0};let t=e.toLowerCase(),o=this.analyticalPatterns.filter(a=>a.test(t)).length,r=this.actionPatterns.filter(a=>a.test(t)).length,s=o/this.analyticalPatterns.length,i=r/this.actionPatterns.length;if(o>r&&o>0){let a=Math.min(s,1);return r>0&&(a=Math.min(a,.5)),{type:"analytical",confidence:a,reasoning:`Matched ${o} analytical patterns${r>0?`, ${r} action patterns (capped confidence)`:""}`}}else return r>o&&r>0?{type:"action",confidence:Math.min(i,1),reasoning:`Matched ${r} action patterns`}:o===r&&o>0?{type:"analytical",confidence:.5,reasoning:`Mixed query (${o} analytical, ${r} action patterns)`}:{type:"conversational",confidence:.3,reasoning:"No strong analytical or action patterns detected"}}getToolRoundsAdjustment(e,t){return e.type==="analytical"&&e.confidence>.6?Math.min(t+3,10):(e.type==="action"&&e.confidence>.6,t)}};c();var No=class{analyzeDependencies(e){let t=[];for(let o=0;o<e.length;o++){let r=e[o],s=[],i=JSON.stringify(r.arguments).toLowerCase();for(let a=0;a<o;a++){let l=e[a];this.hasDependency(r,l,i)&&s.push(l.id)}t.push({toolCallId:r.id,dependsOn:s})}return t}hasDependency(e,t,o){return!!(e.arguments.path&&t.arguments.path&&e.arguments.path===t.arguments.path||e.arguments.file_path&&t.arguments.file_path&&e.arguments.file_path===t.arguments.file_path||e.arguments.filePath&&t.arguments.filePath&&e.arguments.filePath===t.arguments.filePath||["fs.write_file","fs.delete_file","fs.move","fs.copy","fs.replace_in_file","fs.append_file"].includes(e.name)&&t.arguments.path&&o.includes(t.arguments.path.toLowerCase())||e.name==="exec.read_output"&&t.name==="exec.run_background"||e.name==="http.download"&&t.name==="http.get"&&t.arguments.url&&o.includes(t.arguments.url.toLowerCase()))}async executeWithDependencies(e,t,o=5){if(e.length===0)return new Map;let r=this.analyzeDependencies(e),s=new Map,i=new Set;for(;i.size<e.length;){let a=[];for(let p of e){if(i.has(p.id))continue;(r.find(g=>g.toolCallId===p.id)?.dependsOn.every(g=>i.has(g))??!0)&&a.push(p)}if(a.length===0){let p=e.filter(m=>!i.has(m.id));throw new Error(`Circular dependency detected in tool calls: ${p.map(m=>m.name).join(", ")}`)}let l=await this.executeBatchWithLimit(a,t,o);for(let{id:p,result:m}of l)s.set(p,m),i.add(p)}return s}async executeBatchWithLimit(e,t,o){let r=[];if(e.length<=o){let s=e.map(async i=>{let a=await t(i);return{id:i.id,result:a}});return await Promise.all(s)}for(let s=0;s<e.length;s+=o){let a=e.slice(s,s+o).map(async p=>{let m=await t(p);return{id:p.id,result:m}}),l=await Promise.all(a);r.push(...l)}return r}shouldUseParallelExecution(e){return e.length<2?!1:this.analyzeDependencies(e).filter(r=>r.dependsOn.length===0).length>=2}};c();function We(n){for(let e=n.length-1;e>=0;e--){let t=n[e];if(t?.role!=="user")continue;let o=t?.content;return typeof o=="string"?o:Array.isArray(o)?o.map(r=>r?.type==="text"?r.text:"").filter(Boolean).join(`
|
|
288
|
+
`):""}return""}P();var Ni=0;function un(){return Ni+=1,`${Date.now()}-${Ni}`}function Ao(n,e){Ue("debug")&&(y(`[AIClient][${n}] Messages (${e.length}):`),e.forEach((t,o)=>{let r=O(t.content,300);y(`[AIClient][${n}] #${o} role=${t.role} content=${r}`)}))}function Ai(n){let e=We(n).toLowerCase();return e?[/\b(list|show|print|display)\b.*\b(files|folders|directory|dir)\b/,/\b(current|this)\b.*\b(directory|folder|repo|repository)\b/,/\b(read|open|view)\b.*\b(file|log|config|json|yaml|env)\b/,/\b(write|create|update|modify|edit|patch|delete|remove|rename|move|copy)\b.*\b(file|folder|directory)\b/,/\b(run|execute)\b.*\b(command|shell|script|tests?)\b/,/\b(http|get|post|put|delete|download|fetch|curl)\b/,/\b(web|search|scrape|crawl|map)\b/,/https?:\/\//].some(o=>o.test(e)):!1}function Oi(n,e){let t=-1;for(let r=n.length-1;r>=0;r--){let s=n[r];if(s.role==="tool"||s.role==="assistant"&&s.tool_calls&&s.tool_calls.length>0){t=r;break}}if(t===-1)return!1;let o=n.length-1-t;return o>0&&o<=e}function Ii(n){return{openai:"gpt-4.1-mini",anthropic:"claude-3-haiku-20240307",gemini:"gemini-2.0-flash-exp",ollama:"llama3.2"}[n]||"default"}function Ky(n){let e=[],t=0;for(let o=n.length-1;o>=0&&t<2;o--){let r=n[o];if(r.role==="assistant"&&r.tool_calls&&r.tool_calls.length>0){t++;for(let s of r.tool_calls){let i=s.function?.name||"unknown",a=s.function?.arguments,l=`Tool: ${i}`;if(a)try{let p=typeof a=="string"?JSON.parse(a):a;p.url&&(l+=` (URL: ${p.url})`),p.file_path&&(l+=` (File: ${p.file_path})`),p.section&&(l+=` (Section: ${p.section})`),p.query&&(l+=` (Query: ${p.query})`),p.command&&(l+=` (Command: ${p.command.substring(0,50)})`)}catch{}e.push(l)}}}return e.length>0?e.join(", "):"None"}async function Li(n,e,t,o){let r=un();y(`[AIClient][${r}] inferNeedsToolsWithAI() provider=${e} model=${o}`);let s=Ky(t),a=t.filter(p=>p.role==="user").slice(-1)[0]?.content||"",l=`Recent tool usage: ${s}
|
|
141
289
|
|
|
142
|
-
User's new message: "${
|
|
290
|
+
User's new message: "${a}"
|
|
143
291
|
|
|
144
292
|
Does this message:
|
|
145
293
|
1. Ask about the same topic/context as recent tools? OR
|
|
@@ -148,27 +296,33 @@ Does this message:
|
|
|
148
296
|
If the message is general knowledge (math, definitions, explanations) or completely unrelated to recent tool context, answer NO.
|
|
149
297
|
If it asks about the same context OR needs new external information, answer YES.
|
|
150
298
|
|
|
151
|
-
Answer only: YES or NO`;try{let m=((await s.generate({model:r,messages:[{role:"user",content:c}],max_tokens:10,temperature:0})).content||"").trim().toUpperCase(),f=m.startsWith("YES");return y(`[AIClient][${o}] inferNeedsToolsWithAI() context="${n}" message="${i.substring(0,50)}" result=${f} (raw: ${m})`),f}catch(p){return E(`[AIClient][${o}] inferNeedsToolsWithAI() error=${p} - falling back to false`),!1}}function ys(s){let e=Re(s).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/],r=[/\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(o=>o.test(e))&&!r.some(o=>o.test(e))}var io=class extends sg{providers;defaultProvider;toolRegistry;toolsConfig;toolRouter;bm25Engine;queryClassifier;toolOrchestrator;activeMode=null;overrideSystemPrompt;disableBaseContext;toolResultMaxChars;constructor(e){super(),this.providers=new Map(Object.entries(e.providers)),this.defaultProvider=e.defaultProvider,this.toolRegistry=e.toolRegistry,this.toolsConfig=e.toolsConfig||z,this.toolRouter=new ot,this.bm25Engine=new et,this.queryClassifier=new qe,this.toolOrchestrator=new oo,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??z.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.toolRegistry&&this.bm25Engine.index(this.toolRegistry.getAll())}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new H("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let r=this.providers.get(t);if(!r)throw new H(`Provider '${t}' not found`,"PROVIDER_NOT_FOUND",404);return r}setDefaultProvider(e){if(!this.providers.has(e))throw new H(`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,v(`[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()),v(`[AIClient] Re-indexed ${this.bm25Engine.getIndexedCount()} tools for BM25 search`))}clearToolDiscoveryCache(){this.toolRouter.clearDiscoveryCache()}async generate(e,t){let r=this.getProvider(t);try{let o=kr(),n=this.injectBaseAgentContext(e);n=this.injectOverrideSystemPrompt(n),n=this.injectModeSystemPrompt(n);let a=t||this.defaultProvider,i=await this.enrichRequestWithTools(n),c=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",p=(i.tools?.length||0)>0,m=i.tool_choice!=null,f=us(i.messages),h=this.toolsConfig.intelligentToolDetection,b=!1;if(!f&&h?.enabled&&p&&fs(i.messages,h.maxFollowUpMessages)){v(`[AIClient][${o}] Message is after tool call, using AI to infer tool needs`);let R=gs(a||"openai");f=await hs(r,a||"openai",i.messages,R),b=!0}let w=ys(i.messages);!m&&p&&(c==="required"||c==="required_for_actions"&&f)?i.tool_choice="required":!m&&p&&b&&!f&&(i.tool_choice="none",v(`[AIClient][${o}] AI inference determined no tools needed, setting tool_choice=none`));let $=r?.constructor?.name||"UnknownProvider",C={...i,__toolpack_request_id:o};v(`[AIClient][${o}] generate() start provider=${a} class=${$} model=${i.model} messages=${i.messages.length} tools=${i.tools?.length||0} tool_choice=${i.tool_choice??"unset"} policy=${c} needsTools=${f} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),so(o,i.messages);let T=await r.generate(C);if(y(`[AIClient][${o}] generate() initial response finish_reason=${T.finish_reason??"unknown"} tool_calls=${T.tool_calls?.length||0} content_preview=${D(T.content||"",200)}`),this.toolsConfig.enabled&&this.toolsConfig.autoExecute&&this.toolRegistry){let S=Re(i.messages),R=this.queryClassifier.classify(S),I=this.toolsConfig.maxToolRounds,U=this.queryClassifier.getToolRoundsAdjustment(R,I);U!==I?v(`[AIClient][${o}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), adjusted maxToolRounds: ${I} \u2192 ${U}`):y(`[AIClient][${o}] Query classified as ${R.type} (confidence: ${R.confidence.toFixed(2)}), keeping maxToolRounds: ${U}`);let L=0,j=[...i.messages];for(T.tool_calls&&T.tool_calls.length>0&&v(`[AIClient] Received ${T.tool_calls.length} tool call(s): ${T.tool_calls.map(B=>B.name).join(", ")}`);T.tool_calls&&T.tool_calls.length>0&&L<U;){L++,v(`[AIClient][${o}] generate() tool round ${L}/${U} tool_calls=${T.tool_calls.length}`),j.push({role:"assistant",content:T.content||"",tool_calls:T.tool_calls.map(W=>({id:W.id,type:"function",function:{name:W.name,arguments:JSON.stringify(W.arguments)}}))});let B=this.toolOrchestrator.shouldUseParallelExecution(T.tool_calls),Se=3,de=T.tool_calls,ae=T.tool_calls.filter(W=>W.name==="web.fetch");if(ae.length>Se){v(`[AIClient][${o}] Limiting web.fetch calls from ${ae.length} \u2192 ${Se} to prevent context overflow`);let W=ae.slice(0,Se);de=[...T.tool_calls.filter(_=>_.name!=="web.fetch"),...W];let O=ae.slice(Se);for(let _ of O)j.push({role:"tool",tool_call_id:_.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let Z=5e4,le=0;if(B){v(`[AIClient][${o}] Using parallel execution for ${de.length} tools`);let W=await this.toolOrchestrator.executeWithDependencies(de,O=>this.executeTool(O),5),ee=!1;for(let O of de){if(ee){j.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let _=W.get(O.id),te=typeof _=="string"?_:JSON.stringify(_);if(le+te.length>Z){E(`[AIClient][${o}] Tool output budget exceeded (${Z} chars), adding placeholder for remaining tools`),j.push({role:"tool",tool_call_id:O.id,content:"[Skipped: tool output budget exceeded for this round]"}),ee=!0;continue}let oe=typeof _=="string"&&_.length>this.toolResultMaxChars?`${_.slice(0,this.toolResultMaxChars)}
|
|
152
|
-
[TRUNCATED tool result: ${
|
|
153
|
-
[TRUNCATED tool result: ${
|
|
154
|
-
[TRUNCATED tool result: ${
|
|
299
|
+
Answer only: YES or NO`;try{let m=((await n.generate({model:o,messages:[{role:"user",content:l}],max_tokens:10,temperature:0})).content||"").trim().toUpperCase(),d=m.startsWith("YES");return y(`[AIClient][${r}] inferNeedsToolsWithAI() context="${s}" message="${a.substring(0,50)}" result=${d} (raw: ${m})`),d}catch(p){return M(`[AIClient][${r}] inferNeedsToolsWithAI() error=${p} - falling back to false`),!1}}function ji(n){let e=We(n).toLowerCase();if(!e)return!1;let t=[/\b(list|show|print|display)\b.*\b(files|folders|directory|dir)\b/,/\b(current|this)\b.*\b(directory|folder|repo|repository)\b/,/\b(read|open|view)\b.*\b(file|log|config|json|yaml|env)\b/],o=[/\b(write|create|update|modify|edit|patch|delete|remove|rename|move|copy)\b/,/\b(run|execute)\b.*\b(command|shell|script|tests?)\b/,/\b(http|get|post|put|delete|download|fetch|curl)\b/,/\b(web|search|scrape|crawl)\b/];return t.some(r=>r.test(e))&&!o.some(r=>r.test(e))}var Oo=class extends Hy{providers;defaultProvider;toolRegistry;toolsConfig;toolRouter;bm25Engine;queryClassifier;toolOrchestrator;activeMode=null;overrideSystemPrompt;disableBaseContext;toolResultMaxChars;hitlConfig;onToolConfirm;currentRound=0;conversationId;contextWindowConfig;contextWindowStateManager;providerModelCache=new Map;constructor(e){super(),this.providers=new Map(Object.entries(e.providers)),this.defaultProvider=e.defaultProvider,this.toolRegistry=e.toolRegistry,this.toolsConfig=e.toolsConfig||Y,this.toolRouter=new xt,this.bm25Engine=new bt,this.queryClassifier=new Ze,this.toolOrchestrator=new No,this.overrideSystemPrompt=e.systemPrompt,this.disableBaseContext=e.disableBaseContext||!1;let t=this.toolsConfig.resultMaxChars??Y.resultMaxChars??2e4;this.toolResultMaxChars=Number.isFinite(t)&&t>0?t:2e4,this.hitlConfig=e.hitlConfig,this.onToolConfirm=e.onToolConfirm,this.conversationId=e.conversationId,this.contextWindowConfig=e.contextWindowConfig,this.providerModelCache=new Map,this.contextWindowConfig&&this.contextWindowConfig.enabled!==!1&&(this.contextWindowStateManager=Ri(this.contextWindowConfig)),this.toolRegistry&&this.bm25Engine.index(this.toolRegistry.getAll())}getConversationId(){return this.conversationId||"global"}async getModelInfo(e,t){let o=e.name||e.constructor.name,r=this.providerModelCache.get(o);if(!r){try{r=await e.getModels()}catch{r=[]}this.providerModelCache.set(o,r)}return r.find(s=>s.id===t||s.displayName===t)}async countRequestTokens(e,t,o){let r=await t.countTokens(e.messages,o);return typeof r=="number"&&Number.isFinite(r)?r:xi(e.messages,o,t.getDisplayName().toLowerCase())}async pruneConversation(e,t,o){let r=this.contextWindowConfig?.retainSystemMessages??!0,s=e;for(let i=0;i<3;i+=1){let a=await this.countRequestTokens(s,t,s.model);if(a<=o)return s;let l=a-o,p=Ci(s.messages,l,r),m=new Set(p.pruneInfo.removedMessages),d=s.messages.filter(b=>!m.has(b)),g={...s,messages:d};if(this.contextWindowStateManager&&this.contextWindowStateManager.recordPruneOperation(this.getConversationId(),p.tokensReclaimed),await this.countRequestTokens(g,t,g.model)<=o||d.length===s.messages.length)return g;s=g}return e}async pruneToMaxMessageHistory(e){let t=this.contextWindowConfig?.maxMessageHistoryLength;if(!t||e.messages.length<=t)return e;let o=this.contextWindowConfig?.retainSystemMessages??!0,r=[];e.messages.forEach((l,p)=>{o&&l.role==="system"||l.role!=="tool"&&r.push(p)});let s=Math.max(0,e.messages.length-t);if(s===0)return e;let i=new Set(r.slice(0,s)),a=e.messages.filter((l,p)=>!i.has(p));return{...e,messages:a}}async summarizeConversation(e,t){let o=e.messages,r=o.filter(x=>x.role==="system"),s=o.filter(x=>x.role!=="system");if(s.length<4)return e;let i=s.slice(-4),a=s.slice(0,-4);if(a.length<2)return e;let l=this.contextWindowConfig?.summarizerModel||e.model,p=Si(a,{model:l,maxSummaryTokens:500}),m=await t.generate({model:l,messages:p,max_tokens:500,temperature:0,response_format:"text"});if(!m.content)throw new yt("Summarization provider returned no summary",this.getConversationId(),a.length,"invalid_response");let d=await this.countRequestTokens({...e,messages:a},t,l),g=ki(m.content,a,d),w=Pi(g);if(!w.valid)throw new yt(`Summarization result is invalid: ${w.issues.join("; ")}`,this.getConversationId(),a.length,"invalid_quality",m.content);let b=ln(g.summary,a.length),T=[...r,b,...i];return this.contextWindowStateManager&&this.contextWindowStateManager.recordSummarization(this.getConversationId(),g.tokensSaved),{...e,messages:T}}async enforceContextWindow(e,t){if(!this.contextWindowConfig||this.contextWindowConfig.enabled===!1)return e;let o=await this.pruneToMaxMessageHistory(e),r=await this.getModelInfo(t,o.model),s=r?.contextWindow??1e5,i=o.max_tokens??r?.maxOutputTokens??1024,a=this.contextWindowConfig.outputTokenBuffer??1.15,l=vi(i,a),p=Math.max(0,s-l),m=Math.floor(s*((this.contextWindowConfig.pruneThreshold??85)/100)),d=Math.min(p,m),g=await this.countRequestTokens(o,t,o.model);if(this.contextWindowStateManager&&(this.contextWindowStateManager.updateTokenCount(this.getConversationId(),g),g>d&&this.contextWindowStateManager.recordWarning(this.getConversationId())),g<=d)return o;let w=this.contextWindowConfig.strategy??"prune";if(w==="fail"&&g>p)throw new ht("Context window exceeded by request messages",this.getConversationId(),g,p,w);if(w==="summarize")try{let T=await this.summarizeConversation(o,t);if(await this.countRequestTokens(T,t,T.model)<=p)return T;o=await this.pruneConversation(T,t,p)}catch{o=await this.pruneConversation(o,t,p)}else o=await this.pruneConversation(o,t,p);let b=await this.countRequestTokens(o,t,o.model);if(b>p&&w==="fail")throw new ht("Context window exceeded after attempted cleanup",this.getConversationId(),b,p,w);return o}isBypassed(e){let t=this.hitlConfig;if(!t||t.enabled===!1)return!0;let o=t.confirmationMode??"all";if(o==="off"||o==="high-only"&&e.confirmation?.level==="medium")return!0;let r=t.bypass??{};return!!(r.tools?.includes(e.name)||r.categories?.includes(e.category)||e.confirmation&&r.levels?.includes(e.confirmation.level))}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){let t=e||this.defaultProvider;if(!t)throw new A("No provider specified and no default provider configured","NO_PROVIDER_CONFIGURED",400);let o=this.providers.get(t);if(!o)throw new A(`Provider '${t}' not found`,"PROVIDER_NOT_FOUND",404);return o}updateHitlConfig(e){this.hitlConfig=e}getHitlConfig(){return this.hitlConfig}setDefaultProvider(e){if(!this.providers.has(e))throw new A(`Provider '${e}' not found`,"PROVIDER_NOT_FOUND",404);this.defaultProvider=e}getToolRegistry(){return this.toolRegistry}getProviders(){return new Map(this.providers)}setToolRegistry(e){this.toolRegistry=e}setToolsConfig(e){this.toolsConfig=e}setSystemPrompt(e){this.overrideSystemPrompt=e}setMode(e){this.activeMode=e,C(`[AIClient] Mode set to: ${e?e.displayName:"none (cleared)"}`)}getMode(){return this.activeMode}getQueryClassifier(){return this.queryClassifier}reindexTools(){this.toolRegistry&&(this.bm25Engine.index(this.toolRegistry.getAll()),C(`[AIClient] Re-indexed ${this.bm25Engine.getIndexedCount()} tools for BM25 search`))}clearToolDiscoveryCache(){this.toolRouter.clearDiscoveryCache()}async generate(e,t){let o=this.getProvider(t);try{let r=un(),s=this.injectBaseAgentContext(e);s=this.injectOverrideSystemPrompt(s),s=this.injectModeSystemPrompt(s);let i=t||this.defaultProvider,a=await this.enrichRequestWithTools(s),l=a.request,p=a.requestToolMap;l=await this.enforceContextWindow(l,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",d=(l.tools?.length||0)>0,g=l.tool_choice!=null,w=Ai(l.messages),b=this.toolsConfig.intelligentToolDetection,T=!1;if(!w&&b?.enabled&&d&&Oi(l.messages,b.maxFollowUpMessages)){C(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let _=Ii(i||"openai");w=await Li(o,i||"openai",l.messages,_),T=!0}let x=ji(l.messages);!g&&d&&(m==="required"||m==="required_for_actions"&&w)?l.tool_choice="required":!g&&d&&T&&!w&&(l.tool_choice="none",C(`[AIClient][${r}] AI inference determined no tools needed, setting tool_choice=none`));let D=o?.constructor?.name||"UnknownProvider",F={...this.stripRequestTools(l),__toolpack_request_id:r};C(`[AIClient][${r}] generate() start provider=${i} class=${D} model=${l.model} messages=${l.messages.length} tools=${l.tools?.length||0} tool_choice=${l.tool_choice??"unset"} policy=${m} needsTools=${w} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Ao(r,l.messages);let k=await o.generate(F);if(y(`[AIClient][${r}] generate() initial response finish_reason=${k.finish_reason??"unknown"} tool_calls=${k.tool_calls?.length||0} content_preview=${O(k.content||"",200)}`),this.toolsConfig.autoExecute&&(this.toolRegistry||p.size>0)){let $=We(l.messages),_=this.queryClassifier.classify($),E=this.toolsConfig.maxToolRounds,U=this.queryClassifier.getToolRoundsAdjustment(_,E);U!==E?C(`[AIClient][${r}] Query classified as ${_.type} (confidence: ${_.confidence.toFixed(2)}), adjusted maxToolRounds: ${E} \u2192 ${U}`):y(`[AIClient][${r}] Query classified as ${_.type} (confidence: ${_.confidence.toFixed(2)}), keeping maxToolRounds: ${U}`);let X=0,H=[...l.messages];for(k.tool_calls&&k.tool_calls.length>0&&C(`[AIClient] Received ${k.tool_calls.length} tool call(s): ${k.tool_calls.map(Q=>Q.name).join(", ")}`);k.tool_calls&&k.tool_calls.length>0&&X<U;){X++,this.currentRound=X,C(`[AIClient][${r}] generate() tool round ${X}/${U} tool_calls=${k.tool_calls.length}`),H.push({role:"assistant",content:k.content||"",tool_calls:k.tool_calls.map(K=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments)}}))});let Q=this.toolOrchestrator.shouldUseParallelExecution(k.tool_calls),Le=3,Ce=k.tool_calls,ae=k.tool_calls.filter(K=>K.name==="web.fetch");if(ae.length>Le){C(`[AIClient][${r}] Limiting web.fetch calls from ${ae.length} \u2192 ${Le} to prevent context overflow`);let K=ae.slice(0,Le);Ce=[...k.tool_calls.filter(R=>R.name!=="web.fetch"),...K];let q=ae.slice(Le);for(let R of q)H.push({role:"tool",tool_call_id:R.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let le=5e4,Te=0;if(Q){C(`[AIClient][${r}] Using parallel execution for ${Ce.length} tools`);let K=await this.toolOrchestrator.executeWithDependencies(Ce,q=>this.executeTool(q,p),5),ce=!1;for(let q of Ce){if(ce){H.push({role:"tool",tool_call_id:q.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let R=K.get(q.id),pe=typeof R=="string"?R:JSON.stringify(R);if(Te+pe.length>le){M(`[AIClient][${r}] Tool output budget exceeded (${le} chars), adding placeholder for remaining tools`),H.push({role:"tool",tool_call_id:q.id,content:"[Skipped: tool output budget exceeded for this round]"}),ce=!0;continue}let me=typeof R=="string"&&R.length>this.toolResultMaxChars?`${R.slice(0,this.toolResultMaxChars)}
|
|
300
|
+
[TRUNCATED tool result: ${R.length} chars]`:R,je=typeof me=="string"?me:JSON.stringify(me);Te+=je.length,H.push({role:"tool",tool_call_id:q.id,content:me})}y(`[AIClient][${r}] Round tool output size: ${Te} chars (budget: ${le})`)}else{C(`[AIClient][${r}] Using sequential execution for ${Ce.length} tools`);let K=!1;for(let ce of Ce){if(K){H.push({role:"tool",tool_call_id:ce.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let q=await this.executeTool(ce,p),R=typeof q=="string"?q:JSON.stringify(q);if(Te+R.length>le){M(`[AIClient][${r}] Tool output budget exceeded (${le} chars), adding placeholder for remaining tools`),H.push({role:"tool",tool_call_id:ce.id,content:"[Skipped: tool output budget exceeded for this round]"}),K=!0;continue}let pe=typeof q=="string"&&q.length>this.toolResultMaxChars?`${q.slice(0,this.toolResultMaxChars)}
|
|
301
|
+
[TRUNCATED tool result: ${q.length} chars]`:q,me=typeof pe=="string"?pe:JSON.stringify(pe);Te+=me.length,H.push({role:"tool",tool_call_id:ce.id,content:pe})}y(`[AIClient][${r}] Round tool output size: ${Te} chars (budget: ${le})`)}let Qe={...l,messages:H,__toolpack_request_id:r},fe=this.stripRequestTools((await this.enrichRequestWithTools(Qe)).request);fe=await this.enforceContextWindow(fe,o),fe.tool_choice==="required"&&(fe.tool_choice=x?"none":"auto",C(`[AIClient][${r}] generate() followup tool_choice override required->${fe.tool_choice}`)),Ue("debug")&&(y(`[AIClient][${r}] generate() followup request messages=${H.length}`),Ao(r,H)),k=await o.generate(fe),y(`[AIClient][${r}] generate() followup response finish_reason=${k.finish_reason??"unknown"} tool_calls=${k.tool_calls?.length||0} content_preview=${O(k.content||"",200)}`)}}return k}catch(r){throw this.wrapError(r)}}async*stream(e,t){let o=this.getProvider(t);try{let r=un(),s=t||this.defaultProvider,i=this.injectBaseAgentContext(e);i=this.injectOverrideSystemPrompt(i),i=this.injectModeSystemPrompt(i);let a=await this.enrichRequestWithTools(i),l=a.request,p=a.requestToolMap;l=await this.enforceContextWindow(l,o);let m=process.env.TOOLPACK_SDK_TOOL_CHOICE_POLICY||this.toolsConfig.toolChoicePolicy||"auto",d=(l.tools?.length||0)>0,g=l.tool_choice!=null,w=Ai(l.messages),b=this.toolsConfig.intelligentToolDetection,T=!1;if(!w&&b?.enabled&&d&&Oi(l.messages,b.maxFollowUpMessages)){C(`[AIClient][${r}] Message is after tool call, using AI to infer tool needs`);let Q=Ii(s||"openai");w=await Li(o,s||"openai",l.messages,Q),T=!0}let x=ji(l.messages);!g&&d&&(m==="required"||m==="required_for_actions"&&w)?l.tool_choice="required":!g&&d&&T&&!w&&(l.tool_choice="none",C(`[AIClient][${r}] AI inference determined no tools needed, setting tool_choice=none`));let D=o?.constructor?.name||"UnknownProvider",F={...this.stripRequestTools(l),__toolpack_request_id:r};if(C(`[AIClient][${r}] stream() start provider=${s} class=${D} model=${l.model} messages=${l.messages.length} tools=${l.tools?.length||0} tool_choice=${l.tool_choice??"unset"} policy=${m} needsTools=${w} autoExecute=${this.toolsConfig.enabled&&this.toolsConfig.autoExecute}`),Ao(r,l.messages),!this.toolsConfig.autoExecute||!this.toolRegistry&&p.size===0){yield*o.stream(F);return}let k=[...l.messages],$=0,_=We(l.messages),E=this.queryClassifier.classify(_),U=this.toolsConfig.maxToolRounds,X=this.queryClassifier.getToolRoundsAdjustment(E,U);for(X!==U&&C(`[AIClient][${r}] stream() Query classified as ${E.type} (confidence: ${E.confidence.toFixed(2)}), adjusted maxToolRounds: ${U} \u2192 ${X}`);$<=X;){if(e.signal?.aborted){C(`[AIClient][${r}] stream() aborted by signal`);return}let H="",Q=[];$++,this.currentRound=$,C(`[AIClient][${r}] stream() round_start ${$}/${X}`);let Le=null,Ce={...l,messages:k},ae=this.stripRequestTools((await this.enrichRequestWithTools(Ce)).request);ae=await this.enforceContextWindow(ae,o),$>0&&ae.tool_choice==="required"&&(ae.tool_choice=x?"none":"auto",C(`[AIClient][${r}] stream() round_${$+1} tool_choice override required->${ae.tool_choice}`));for await(let R of o.stream(ae)){if(e.signal?.aborted){C(`[AIClient][${r}] stream() aborted by signal during chunk processing`);return}R.tool_calls&&R.tool_calls.length>0&&(Q.push(...R.tool_calls),y(`[AIClient][${r}] stream() tool_calls_chunk count=${R.tool_calls.length} names=${R.tool_calls.map(pe=>pe.name).join(", ")}`),yield R),R.delta&&(H+=R.delta,yield R),R.finish_reason&&(Le=R.finish_reason),R.finish_reason==="stop"&&(yield R)}if(y(`[AIClient][${r}] stream() round_end finish_reason=${Le??"unknown"} accumulated_len=${H.length} tool_calls_total=${Q.length} content_preview=${O(H,200)}`),Q.length===0)break;if(C(`[AIClient][${r}] stream() received ${Q.length} tool call(s): ${Q.map(R=>R.name).join(", ")}`),$++,$>X){C(`[AIClient][${r}] stream() max tool rounds (${X}) reached`);break}C(`[AIClient][${r}] stream() tool round ${$}/${X}`),k.push({role:"assistant",content:H||"",tool_calls:Q.map(R=>({id:R.id,type:"function",function:{name:R.name,arguments:JSON.stringify(R.arguments)}}))});let le=3,Te=Q,Qe=Q.filter(R=>R.name==="web.fetch");if(Qe.length>le){C(`[AIClient][${r}] Limiting web.fetch calls from ${Qe.length} \u2192 ${le} to prevent context overflow`);let R=Qe.slice(0,le);Te=[...Q.filter(je=>je.name!=="web.fetch"),...R];let me=Qe.slice(le);for(let je of me)k.push({role:"tool",tool_call_id:je.id,content:"[Skipped: web.fetch fan-out limit exceeded]"})}let fe=5e4,K=0,ce=!1,q=[];for(let R of Te){if(ce){k.push({role:"tool",tool_call_id:R.id,content:"[Skipped: tool output budget exceeded for this round]"});continue}let pe=Date.now(),me=!1,je=setInterval(()=>{me||q.push({delta:""})},500),Pe=await this.executeTool(R,p);me=!0,clearInterval(je);let xy=Date.now()-pe;for(;q.length>0;)yield q.shift();await new Promise(Py=>setTimeout(Py,0));let vy=typeof Pe=="string"?Pe:JSON.stringify(Pe);if(K+vy.length>fe){M(`[AIClient][${r}] Tool output budget exceeded (${fe} chars), adding placeholder for remaining tools`),k.push({role:"tool",tool_call_id:R.id,content:"[Skipped: tool output budget exceeded for this round]"}),ce=!0;continue}let Fe=typeof Pe=="string"&&Pe.length>this.toolResultMaxChars?`${Pe.slice(0,this.toolResultMaxChars)}
|
|
302
|
+
[TRUNCATED tool result: ${Pe.length} chars]`:Pe,Cy=typeof Fe=="string"?Fe:JSON.stringify(Fe);K+=Cy.length,k.push({role:"tool",tool_call_id:R.id,content:Fe}),yield{delta:"",tool_calls:[{...R,result:typeof Fe=="string"?Fe:JSON.stringify(Fe),duration:xy}]}}y(`[AIClient][${r}] Round tool output size: ${K} chars (budget: ${fe})`),Ue("debug")&&(y(`[AIClient][${r}] stream() after_tools messages=${k.length}`),Ao(r,k))}}catch(r){throw this.wrapError(r)}}async embed(e,t){let o=this.getProvider(t);try{return await o.embed(e)}catch(r){throw this.wrapError(r)}}async enrichRequestWithTools(e){if(this.activeMode?.blockAllTools)return C(`[AIClient] Mode "${this.activeMode.displayName}" blocks all tools`),{request:e,requestToolMap:new Map};let t=this.buildRequestToolMap(e.requestTools),o=Array.from(t.values()).map(m=>this.requestToolToSchema(m)),r=t.size>0;if(!this.toolsConfig.enabled&&!r)return y("[AIClient] Tools disabled and no request-scoped tools"),{request:e,requestToolMap:t};let s=this.toolsConfig;if(this.activeMode?.toolSearch&&this.toolsConfig.toolSearch&&(s={...this.toolsConfig,toolSearch:{...this.toolsConfig.toolSearch,...this.activeMode.toolSearch.enabled!==void 0?{enabled:this.activeMode.toolSearch.enabled}:{},...this.activeMode.toolSearch.alwaysLoadedTools?{alwaysLoadedTools:this.activeMode.toolSearch.alwaysLoadedTools}:{},...this.activeMode.toolSearch.alwaysLoadedCategories?{alwaysLoadedCategories:this.activeMode.toolSearch.alwaysLoadedCategories}:{}}},y(`[AIClient] Merged mode toolSearch config: enabled=${s.toolSearch?.enabled}, alwaysLoadedTools=${s.toolSearch?.alwaysLoadedTools?.length||0}`)),e.tools&&e.tools.length>0){if(!s.toolSearch?.enabled||!this.toolRegistry){y(`[AIClient] Request already has ${e.tools.length} tools`);let b=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(o)),T=b===e.tools?e:{...e,tools:b};return{request:this.injectRequestToolGuidance(T,b),requestToolMap:t}}let m=await this.toolRouter.resolve(e.messages,this.toolRegistry,s);if(y(`[AIClient] Resolved ${m.length} tools to send: ${m.map(b=>b.name).join(", ")||"none"}`),this.activeMode&&m.length>0){let b=m.length;m=this.filterSchemasByMode(m,this.activeMode);let T=b-m.length;T>0&&C(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${T} tools`)}let d=new Set(e.tools.map(b=>b.function.name)),g=m.filter(b=>!d.has(b.name)).map(b=>({type:"function",function:{name:b.name,description:b.description,parameters:b.parameters}}));if(g.length===0){y(`[AIClient] Request already has ${e.tools.length} tools (no new discoveries)`);let b=this.mergeToolCallRequests(e.tools,this.schemasToToolCallRequests(o)),T=b===e.tools?e:{...e,tools:b};return{request:this.injectRequestToolGuidance(T,b),requestToolMap:t}}let w={...e,tools:this.mergeToolCallRequests([...e.tools,...g],this.schemasToToolCallRequests(o))};return s.toolSearch?.enabled&&this.toolRegistry&&(w=this.injectToolSearchPrompt(w)),{request:this.injectRequestToolGuidance(w,w.tools),requestToolMap:t}}if(!this.toolRegistry){y("[AIClient] Tool registry not configured, skipping tool resolution");let m=this.schemasToToolCallRequests(o),d=m.length>0?{...e,tools:m}:e;return{request:this.injectRequestToolGuidance(d,m),requestToolMap:t}}let i=this.toolRegistry,a=await this.toolRouter.resolve(e.messages,i,s);if(y(`[AIClient] Resolved ${a.length} tools to send: ${a.map(m=>m.name).join(", ")||"none"}`),this.activeMode&&a.length>0){let m=a.length;a=this.filterSchemasByMode(a,this.activeMode);let d=m-a.length;d>0&&C(`[AIClient] Mode "${this.activeMode.displayName}" filtered out ${d} tools`)}let l=this.schemasToToolCallRequests(this.mergeSchemas(a,o));if(l.length===0)return{request:e,requestToolMap:t};let p={...e,tools:l};return this.toolsConfig.toolSearch?.enabled&&i&&(p=this.injectToolSearchPrompt(p)),{request:this.injectRequestToolGuidance(p,l),requestToolMap:t}}buildRequestToolMap(e){let t=new Map;for(let o of e||[])t.set(o.name,o);return t}requestToolToSchema(e){return{name:e.name,displayName:e.displayName,description:e.description,parameters:e.parameters,category:e.category,cacheable:e.cacheable}}mergeSchemas(e,t){let o=new Map;for(let r of e)o.set(r.name,r);for(let r of t)o.set(r.name,r);return Array.from(o.values())}schemasToToolCallRequests(e){return e.map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.parameters}}))}mergeToolCallRequests(e,t){if(t.length===0)return e;let o=new Map;for(let r of e)o.set(r.function.name,r);for(let r of t)o.set(r.function.name,r);return Array.from(o.values())}injectRequestToolGuidance(e,t){let o=new Set((t||e.tools||[]).map(l=>l.function.name));if(o.size===0)return e;let r="<!-- TOOLPACK_REQUEST_TOOL_GUIDANCE -->",s=[];if(o.has("knowledge_search")||o.has("knowledge_add")){let l=["Knowledge Base:"];o.has("knowledge_search")&&l.push("- Use `knowledge_search` when you need factual or domain-specific information that may already be stored."),o.has("knowledge_add")&&l.push("- Use `knowledge_add` when you encounter a durable fact, user preference, or decision that future conversations should know. Do not add confidential information, routine task outputs, or context that is specific to this conversation only."),s.push(l.join(`
|
|
303
|
+
`))}if(o.has("conversation_search")&&s.push("Conversation History:\n- Only recent messages may be present in context.\n- Use `conversation_search` to find relevant details from earlier in this conversation when needed."),s.length===0)return e;let i=`${r}
|
|
304
|
+
${s.join(`
|
|
305
|
+
|
|
306
|
+
`)}`,a=e.messages.findIndex(l=>l.role==="system");if(a>=0){let l=e.messages.map((p,m)=>{if(m!==a)return p;let d=typeof p.content=="string"?p.content:"";return d.includes(r)?p:{...p,content:`${d}
|
|
307
|
+
|
|
308
|
+
${i}`.trim()}});return{...e,messages:l}}return{...e,messages:[{role:"system",content:i},...e.messages]}}stripRequestTools(e){let{requestTools:t,...o}=e;return o}filterSchemasByMode(e,t){return e.filter(o=>{if(t.blockedTools.includes(o.name)||t.blockedToolCategories.includes(o.category))return!1;if(Mo(o.name)){let i=t.toolSearch?.enabled;if(i!==void 0?i:this.toolsConfig.toolSearch?.enabled??!1)return!0}let r=t.allowedTools.length>0,s=t.allowedToolCategories.length>0;if(r||s){let i=r&&t.allowedTools.includes(o.name),a=s&&t.allowedToolCategories.includes(o.category);return i||a}return!0})}injectModeSystemPrompt(e){if(!this.activeMode||!this.activeMode.systemPrompt)return y(`[AIClient] injectModeSystemPrompt: No active mode or empty systemPrompt. activeMode=${this.activeMode?.name}, systemPrompt=${this.activeMode?.systemPrompt?.substring(0,50)}`),e;let t=this.activeMode.systemPrompt;if(y(`[AIClient] injectModeSystemPrompt: Injecting mode prompt for ${this.activeMode.name}, length=${t.length}`),e.messages.some(r=>r.role==="system")){let r=e.messages.map(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
|
|
155
309
|
|
|
156
|
-
${t}`}}return
|
|
310
|
+
${t}`}}return s});return{...e,messages:r}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectOverrideSystemPrompt(e){if(!this.overrideSystemPrompt)return e;let t=this.overrideSystemPrompt;if(e.messages.some(r=>r.role==="system")){let r=e.messages.map(s=>{if(s.role==="system"){let i=typeof s.content=="string"?s.content:"";return{...s,content:`${i}
|
|
157
311
|
|
|
158
|
-
${t}`}}return
|
|
312
|
+
${t}`}}return s});return{...e,messages:r}}else return{...e,messages:[{role:"system",content:t},...e.messages]}}injectBaseAgentContext(e){let t=!0,o=!0,r,s=this.disableBaseContext;if(this.activeMode?.baseContext===!1)return e;this.activeMode?.baseContext&&(t=this.activeMode.baseContext.includeWorkingDirectory!==!1,o=this.activeMode.baseContext.includeToolCategories!==!1,r=this.activeMode.baseContext.custom);let i=r||$i({workingDirectory:process.cwd(),toolCategories:this.toolRegistry?this.toolRegistry.getCategories():[],disabled:s,includeWorkingDirectory:t,includeToolCategories:o});if(!i)return e;if(e.messages.some(l=>l.role==="system")){let l=e.messages.map(p=>{if(p.role==="system"){let m=typeof p.content=="string"?p.content:"";return{...p,content:`${i}
|
|
159
313
|
|
|
160
|
-
${m}`}}return p});return{...e,messages:
|
|
161
|
-
`);
|
|
314
|
+
${m}`}}return p});return{...e,messages:l}}else return{...e,messages:[{role:"system",content:i},...e.messages]}}injectToolSearchPrompt(e){if(!this.toolRegistry)return e;let t=e.messages.some(i=>i.role==="system"),o=this.toolsConfig.toolSearch?.alwaysLoadedTools??[],r="";if(o.length>0){let i=o.map(a=>{let l=this.toolRegistry?.get(a);return l?` - **${l.name}**: ${l.description}`:null}).filter(Boolean).join(`
|
|
315
|
+
`);i&&(r=`
|
|
162
316
|
|
|
163
317
|
You have these tools always available:
|
|
164
|
-
${
|
|
318
|
+
${i}
|
|
165
319
|
|
|
166
|
-
Use these tools directly when appropriate for the task.`)}let
|
|
320
|
+
Use these tools directly when appropriate for the task.`)}let s=`
|
|
167
321
|
IMPORTANT: Tool Discovery Instructions
|
|
168
322
|
|
|
169
|
-
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.${
|
|
323
|
+
You have access to a limited set of tools. If you need a tool that is not in your current list, you MUST use the 'tool.search' tool to discover it.${r}
|
|
170
324
|
|
|
171
|
-
${
|
|
325
|
+
${pn(this.toolRegistry)}
|
|
172
326
|
|
|
173
327
|
When you need a tool:
|
|
174
328
|
1. Check if it's in your current tool list
|
|
@@ -176,30 +330,35 @@ When you need a tool:
|
|
|
176
330
|
3. After discovering tools, you can call them directly in subsequent turns
|
|
177
331
|
|
|
178
332
|
NEVER guess or hallucinate tool names. ALWAYS use tool.search to discover tools you don't have.
|
|
179
|
-
`.trim();if(t){let
|
|
333
|
+
`.trim();if(t){let i=e.messages.map(a=>{if(a.role==="system"){let l=typeof a.content=="string"?a.content:"";return{...a,content:`${l}
|
|
180
334
|
|
|
181
|
-
${n}`}}return i});return{...e,messages:a}}else return{...e,messages:[{role:"system",content:n},...e.messages]}}async executeTool(e){let t=Date.now();if(this.emit("tool:started",{toolName:e.name,toolCallId:e.id,status:"started",args:e.arguments}),v(`[AIClient] Executing tool: ${e.name} with args: ${D(e.arguments,500)}`),!this.toolRegistry){let o="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:o,duration:Date.now()-t}),JSON.stringify({error:o})}if(vr(e.name)){let o=this.executeToolSearch(e.arguments),n=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof o=="string"?o.substring(0,200):JSON.stringify(o).substring(0,200),duration:n}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:o,duration:n,status:"success",timestamp:Date.now()}),o}let r=this.toolRegistry.get(e.name);if(!r){E(`[AIClient] Tool '${e.name}' not found in registry`);let o=this.findSimilarToolName(e.name),n=o?`Tool '${e.name}' not found. Did you mean '${o}'? 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:n,duration:Date.now()-t}),JSON.stringify({error:n})}try{let o={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:i=>v(`[Tool] ${i}`)},n=await r.execute(e.arguments,o),a=Date.now()-t;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof n=="string"?n.substring(0,200):JSON.stringify(n).substring(0,200),duration:a}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:n,duration:a,status:"success",timestamp:Date.now()}),v(`[AIClient] Tool ${e.name} executed successfully in ${a}ms result_len=${n?.length??0}`),Ee("debug")&&y(`[AIClient] Tool ${e.name} result_preview=${D(n,400)}`),n}catch(o){let n=Date.now()-t,a=o.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:a,duration:n}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:a}),duration:n,status:"error",timestamp:Date.now()}),Q(`[AIClient] Tool ${e.name} failed: ${D(a,300)}`),JSON.stringify({error:a})}}findSimilarToolName(e){if(!this.toolRegistry)return null;let t=this.toolRegistry.getAll(),r=e.replace(/_/g,".");if(t.some(c=>c.name===r))return r;let o=e.replace(/\./g,"_");if(t.some(c=>c.name===o))return o;let n=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(c=>c.name===n))return n;let a=null,i=1/0;for(let c of t){let p=this.levenshteinDistance(e.toLowerCase(),c.name.toLowerCase());p<=2&&p<i&&(i=p,a=c.name)}return a}levenshteinDistance(e,t){let r=[];for(let o=0;o<=t.length;o++)r[o]=[o];for(let o=0;o<=e.length;o++)r[0][o]=o;for(let o=1;o<=t.length;o++)for(let n=1;n<=e.length;n++)t.charAt(o-1)===e.charAt(n-1)?r[o][n]=r[o-1][n-1]:r[o][n]=Math.min(r[o-1][n-1]+1,r[o][n-1]+1,r[o-1][n]+1);return r[t.length][e.length]}executeToolSearch(e){let{query:t,category:r}=e,o=this.toolsConfig.toolSearch?.searchResultLimit??5;v(`[AIClient] Executing tool.search: query="${t}" category=${r||"all"} limit=${o}`);let n=this.bm25Engine.search(t,{limit:o,category:r}),a=n.map(i=>i.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,a),y(`[AIClient] tool.search found ${n.length} tools: ${a.join(", ")||"none"}`),JSON.stringify({query:t,found:n.length,tools:n.map(i=>({name:i.tool.name,displayName:i.tool.displayName,description:i.tool.description,category:i.tool.category,parameters:i.tool.parameters,relevanceScore:Math.round(i.score*100)/100})),hint:n.length>0?`Found ${n.length} tools. You can now call any of these tools directly.`:`No tools found for "${t}". Try a different search term.`})}wrapError(e){return e instanceof H?e:new F(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};l();l();import Ss from"@anthropic-ai/sdk";l();ce();var Y=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()}`)}};ce();k();var ao=class extends Y{client;constructor(e,t){super(),this.client=new Ss({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(o=>this.sanitizeToolName(o.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,r=await this.toAnthropicMessages(e.messages,e.mediaOptions),o=r.system,n=r.userMessages,a={model:e.model,messages:n,system:o,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!1};e.tools&&e.tools.length>0?(a.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?a.tool_choice={type:"any"}:e.tool_choice==="none"?delete a.tools:a.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${a.tools?.length||0} tools with tool_choice: ${a.tool_choice?.type||"unset"}`),a.tools&&a.tools.length>0&&y(`[Anthropic][${t}] First tool: ${D(a.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] generate() request: model=${a.model}, messages=${a.messages.length}, tools=${a.tools?.length||0}, tool_choice=${a.tool_choice?.type??"unset"}`),V(t,"Anthropic",a.messages);let i=await this.client.messages.create(a,e.signal?{signal:e.signal}:void 0),c=[],p=[];for(let m of i.content)m.type==="text"?c.push(m.text):m.type==="tool_use"&&p.push({id:m.id,name:this.restoreToolName(m.name,e.tools),arguments:m.input});return y(`[Anthropic][${t}] Response finish_reason=${i.stop_reason} tool_calls=${p.length} content_preview=${D(c.join(""),200)}`),{content:c.length>0?c.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:p.length>0?p:void 0,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,r=await this.toAnthropicMessages(e.messages,e.mediaOptions),o={model:e.model,messages:r.userMessages,system:r.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(o.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?o.tool_choice={type:"any"}:e.tool_choice==="none"?delete o.tools:o.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${o.tools?.length||0} tools with tool_choice: ${o.tool_choice?.type||"unset"}`),o.tools&&o.tools.length>0&&y(`[Anthropic][${t}] First tool: ${D(o.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${o.model}, messages=${o.messages.length}, tools=${o.tools?.length||0}, tool_choice=${o.tool_choice?.type??"unset"}`),V(t,"Anthropic",o.messages);let n=await this.client.messages.create(o,e.signal?{signal:e.signal}:void 0),a="",i="",c="",p=!1;for await(let m of n)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,a=m.content_block.id,i=m.content_block.name,c=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(c+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(y(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${i}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:a,name:this.restoreToolName(i,e.tools),arguments:JSON.parse(c||"{}")}]},p=!1),m.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 M("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let r,o=[],{normalizeImagePart:n}=await Promise.resolve().then(()=>(Ue(),st));for(let a of e)if(a.role==="system"){if(typeof a.content=="string")r=a.content;else if(a.content!==null){let i=a.content.filter(c=>typeof c=="object"&&c.type==="text").map(c=>c.text).join(`
|
|
182
|
-
`);
|
|
183
|
-
`);
|
|
335
|
+
${s}`}}return a});return{...e,messages:i}}else return{...e,messages:[{role:"system",content:s},...e.messages]}}async executeTool(e,t){let o=Date.now();this.emit("tool:started",{toolName:e.name,toolCallId:e.id,status:"started",args:e.arguments}),C(`[AIClient] Executing tool: ${e.name} with args: ${O(e.arguments,500)}`);let r=t.get(e.name),s=r?void 0:this.toolRegistry?.get(e.name);if(!r&&!this.toolRegistry){let a="No tool registry configured";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:a,duration:Date.now()-o}),JSON.stringify({error:a})}if(Mo(e.name)){let a=this.executeToolSearch(e.arguments),l=Date.now()-o;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof a=="string"?a.substring(0,200):JSON.stringify(a).substring(0,200),duration:l}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:a,duration:l,status:"success",timestamp:Date.now()}),a}let i=r||s;if(!i){M(`[AIClient] Tool '${e.name}' not found in registry`);let a=this.findSimilarToolName(e.name),l=a?`Tool '${e.name}' not found. Did you mean '${a}'? Use tool.search to discover available tools.`:`Tool '${e.name}' not found. Use tool.search to discover available tools.`;return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:l,duration:Date.now()-o}),JSON.stringify({error:l})}try{let a=e.arguments;if(s?.confirmation&&this.onToolConfirm&&!this.isBypassed(s)){this.emit("tool:confirmation_requested",{tool:s,args:a,level:s.confirmation.level,reason:s.confirmation.reason});let g=await this.onToolConfirm(s,a,{roundNumber:this.currentRound,conversationId:this.conversationId});if(this.emit("tool:confirmation_resolved",{tool:s,args:a,level:s.confirmation.level,reason:s.confirmation.reason,decision:g}),g.action==="deny"){let w=`[Execution denied by user${g.reason?": "+g.reason:""}]`,b=Date.now()-o;return this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:w,duration:b}),this.emit("tool:log",{id:e.id,name:e.name,arguments:a,result:w,duration:b,status:"success",timestamp:Date.now()}),w}g.action==="modify"&&(a=g.args)}let l={workspaceRoot:process.cwd(),config:this.toolsConfig?.additionalConfigurations??{},log:g=>C(`[Tool] ${g}`)},p=r?await r.execute(a):await i.execute(a,l),m=Date.now()-o;this.emit("tool:completed",{toolName:e.name,toolCallId:e.id,status:"completed",result:typeof p=="string"?p.substring(0,200):JSON.stringify(p).substring(0,200),duration:m}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:p,duration:m,status:"success",timestamp:Date.now()});let d=typeof p=="string"?p.length:JSON.stringify(p).length;return C(`[AIClient] Tool ${e.name} executed successfully in ${m}ms result_len=${d}`),Ue("debug")&&y(`[AIClient] Tool ${e.name} result_preview=${O(p,400)}`),typeof p=="string"?p:JSON.stringify(p)}catch(a){let l=Date.now()-o,p=a.message||"Tool execution failed";return this.emit("tool:failed",{toolName:e.name,toolCallId:e.id,status:"failed",error:p,duration:l}),this.emit("tool:log",{id:e.id,name:e.name,arguments:e.arguments,result:JSON.stringify({error:p}),duration:l,status:"error",timestamp:Date.now()}),ee(`[AIClient] Tool ${e.name} failed: ${O(p,300)}`),JSON.stringify({error:p})}}findSimilarToolName(e){if(!this.toolRegistry)return null;let t=this.toolRegistry.getAll(),o=e.replace(/_/g,".");if(t.some(l=>l.name===o))return o;let r=e.replace(/\./g,"_");if(t.some(l=>l.name===r))return r;let s=e.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase().replace(/_/g,".");if(t.some(l=>l.name===s))return s;let i=null,a=1/0;for(let l of t){let p=this.levenshteinDistance(e.toLowerCase(),l.name.toLowerCase());p<=2&&p<a&&(a=p,i=l.name)}return i}levenshteinDistance(e,t){let o=[];for(let r=0;r<=t.length;r++)o[r]=[r];for(let r=0;r<=e.length;r++)o[0][r]=r;for(let r=1;r<=t.length;r++)for(let s=1;s<=e.length;s++)t.charAt(r-1)===e.charAt(s-1)?o[r][s]=o[r-1][s-1]:o[r][s]=Math.min(o[r-1][s-1]+1,o[r][s-1]+1,o[r-1][s]+1);return o[t.length][e.length]}executeToolSearch(e){let{query:t,category:o}=e,r=this.toolsConfig.toolSearch?.searchResultLimit??5,s=typeof o=="string"&&o.length>0?o:void 0;if(this.activeMode&&!(this.filterSchemasByMode([Tt()],this.activeMode).length>0))return M("[AIClient] tool.search blocked by active mode"),JSON.stringify({query:t,found:0,tools:[],hint:"tool.search is not allowed in the current mode."});C(`[AIClient] Executing tool.search: query="${t}" category=${s||"all"} limit=${r}`);let i=this.activeMode?Math.max(r*4,r):r,a=this.bm25Engine.search(t,{limit:i,category:s});if(this.activeMode&&a.length>0){let p=this.filterSchemasByMode(a.map(w=>w.tool),this.activeMode),m=new Set(p.map(w=>w.name)),d=a.length;a=a.filter(w=>m.has(w.toolName));let g=d-a.length;g>0&&y(`[AIClient] tool.search filtered out ${g} disallowed results for mode "${this.activeMode.displayName}"`)}a.length>r&&(a=a.slice(0,r));let l=a.map(p=>p.toolName);return this.toolRouter.getDiscoveryCache().recordDiscovery(t,l),y(`[AIClient] tool.search found ${a.length} tools: ${l.join(", ")||"none"}`),JSON.stringify({query:t,found:a.length,tools:a.map(p=>({name:p.tool.name,displayName:p.tool.displayName,description:p.tool.description,category:p.tool.category,parameters:p.tool.parameters,relevanceScore:Math.round(p.score*100)/100})),hint:a.length>0?`Found ${a.length} tools. You can now call any of these tools directly.`:`No tools found for "${t}". Try a different search term.`})}wrapError(e){return e instanceof A?e:new W(e.message||"Unknown provider error","UNKNOWN_PROVIDER_ERROR",500,e)}};c();c();import Hi from"@anthropic-ai/sdk";c();ne();var te=class{name;async getModels(){return[]}getDisplayName(){return this.name||this.constructor.name.replace(/Adapter$/,"")}supportsFileUpload(){return!1}async uploadFile(e){throw new j(`File upload API is not supported by ${this.getDisplayName()}`)}async deleteFile(e){throw new j(`File deletion API is not supported by ${this.getDisplayName()}`)}async countTokens(e,t){return null}};ne();P();var Io=class extends te{client;constructor(e,t){super(),this.client=new Hi({apiKey:e,baseURL:t})}supportsFileUpload(){return!0}async uploadFile(e){try{let t=await import("fs");if(!e.filePath)throw new j("Anthropic uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"Anthropic"}async getModels(){return[{id:"claude-haiku-4-5-20251001",displayName:"Claude Haiku 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:64e3},{id:"claude-sonnet-4-5-20250929",displayName:"Claude Sonnet 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-sonnet-4-6",displayName:"Claude Sonnet 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-5",displayName:"Claude Opus 4.5",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384},{id:"claude-opus-4-6",displayName:"Claude Opus 4.6",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:2e5,maxOutputTokens:16384}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),r=o.system,s=o.userMessages,i={model:e.model,messages:s,system:r,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!1};e.tools&&e.tools.length>0?(i.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?i.tool_choice={type:"any"}:e.tool_choice==="none"?delete i.tools:i.tool_choice={type:"auto"},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: ${O(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"}`),se(t,"Anthropic",i.messages);let a=await this.client.messages.create(i,e.signal?{signal:e.signal}:void 0),l=[],p=[];for(let m of a.content)m.type==="text"?l.push(m.text):m.type==="tool_use"&&p.push({id:m.id,name:this.restoreToolName(m.name,e.tools),arguments:m.input});return y(`[Anthropic][${t}] Response finish_reason=${a.stop_reason} tool_calls=${p.length} content_preview=${O(l.join(""),200)}`),{content:l.length>0?l.join(""):null,usage:{prompt_tokens:a.usage.input_tokens,completion_tokens:a.usage.output_tokens,total_tokens:a.usage.input_tokens+a.usage.output_tokens},finish_reason:this.mapFinishReason(a.stop_reason),tool_calls:p.length>0?p:void 0,raw:a}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await this.toAnthropicMessages(e.messages,e.mediaOptions),r={model:e.model,messages:o.userMessages,system:o.system,max_tokens:e.max_tokens||4096,temperature:e.temperature,top_p:e.top_p,stream:!0};e.tools&&e.tools.length>0?(r.tools=e.tools.map(m=>({name:this.sanitizeToolName(m.function.name),description:m.function.description,input_schema:m.function.parameters})),e.tool_choice==="required"?r.tool_choice={type:"any"}:e.tool_choice==="none"?delete r.tools:r.tool_choice={type:"auto"},y(`[Anthropic][${t}] Sending ${r.tools?.length||0} tools with tool_choice: ${r.tool_choice?.type||"unset"}`),r.tools&&r.tools.length>0&&y(`[Anthropic][${t}] First tool: ${O(r.tools[0],800)}`)):y(`[Anthropic][${t}] NO TOOLS in request`),y(`[Anthropic][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice?.type??"unset"}`),se(t,"Anthropic",r.messages);let s=await this.client.messages.create(r,e.signal?{signal:e.signal}:void 0),i="",a="",l="",p=!1;for await(let m of s)m.type==="content_block_start"&&m.content_block?.type==="tool_use"&&(p=!0,i=m.content_block.id,a=m.content_block.name,l=""),m.type==="content_block_delta"&&(m.delta.type==="text_delta"?yield{delta:m.delta.text}:m.delta.type==="input_json_delta"&&p&&(l+=m.delta.partial_json)),m.type==="content_block_stop"&&p&&(y(`[Anthropic][${t}] Stream finish_reason=tool_calls accumulated_call=${a}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:i,name:this.restoreToolName(a,e.tools),arguments:JSON.parse(l||"{}")}]},p=!1),m.type==="message_stop"&&($e(`[Anthropic][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"})}catch(t){throw this.handleError(t)}}async embed(e){throw new j("Embeddings are not strictly supported by the Anthropic API currently.")}async toAnthropicMessages(e,t={}){let o,r=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(tt(),St));for(let i of e)if(i.role==="system"){if(typeof i.content=="string")o=i.content;else if(i.content!==null){let a=i.content.filter(l=>typeof l=="object"&&l.type==="text").map(l=>l.text).join(`
|
|
336
|
+
`);a&&(o=a)}}else if(i.role==="tool"&&i.tool_call_id)r.push({role:"user",content:[{type:"tool_result",tool_use_id:i.tool_call_id,content:typeof i.content=="string"?i.content:JSON.stringify(i.content)}]});else if(i.role==="assistant"&&i.tool_calls&&i.tool_calls.length>0){let a=[];if(typeof i.content=="string"&&i.content)a.push({type:"text",text:i.content});else if(Array.isArray(i.content)){let l=i.content.filter(p=>typeof p=="object"&&p.type==="text").map(p=>p.text).join(`
|
|
337
|
+
`);l&&a.push({type:"text",text:l})}for(let l of i.tool_calls)a.push({type:"tool_use",id:l.id,name:this.sanitizeToolName(l.function.name),input:typeof l.function.arguments=="string"?JSON.parse(l.function.arguments||"{}"):l.function.arguments});r.push({role:"assistant",content:a})}else{let a=[];typeof i.content=="string"?a=i.content:i.content!==null&&(a=(await Promise.all(i.content.map(async l=>{if(l.type==="text")return{type:"text",text:l.text};if(l.type==="image_url"){let p=l.image_url.url;if(p.startsWith("data:")){let m=p.match(/^data:(image\/\w+);base64,(.+)$/);if(m)return{type:"image",source:{type:"base64",media_type:m[1],data:m[2]}}}return{type:"image",source:{type:"url",url:p}}}if(l.type==="image_data"||l.type==="image_file"){let{data:p,mimeType:m}=await s(l);return{type:"image",source:{type:"base64",media_type:m,data:p}}}return null}))).filter(Boolean)),r.push({role:i.role==="user"?"user":"assistant",content:a})}return{system:o,userMessages:r}}mapFinishReason(e){return e==="end_turn"?"stop":e==="max_tokens"?"length":e==="stop_sequence"?"stop":e}handleError(e){if(e instanceof Hi.APIError){let t=e.message;return e.status===401?new Se(t,e):e.status===429?new ke(t,void 0,e):e.status&&e.status>=400&&e.status<500?new j(t,e):new W(t,"ANTHROPIC_ERROR",e.status||500,e)}return new W("Unknown Anthropic error","UNKNOWN",500,e)}};c();import{GoogleGenerativeAI as Xy}from"@google/generative-ai";ne();P();var Lo=class extends te{genAI;constructor(e){super(),this.genAI=new Xy(e)}supportsFileUpload(){return!0}sanitizeSchema(e){if(!e||typeof e!="object")return e;let t={};for(let[o,r]of Object.entries(e))o==="additionalProperties"||o==="exclusiveMinimum"||o==="exclusiveMaximum"||o==="$schema"||o==="$id"||o==="definitions"||o==="$defs"||(typeof r=="object"&&r!==null?Array.isArray(r)?t[o]=r.map(s=>this.sanitizeSchema(s)):t[o]=this.sanitizeSchema(r):t[o]=r);return t}async uploadFile(e){try{let t=await import("fs"),o=await import("path");if(!e.filePath)throw new j("Gemini uploadFile requires a filePath.");let r=await t.promises.readFile(e.filePath),s=o.basename(e.filePath),i=e.mimeType||"application/octet-stream",l=`https://generativelanguage.googleapis.com/upload/v1beta/files?key=${this.genAI.apiKey}`,p="----WebKitFormBoundary"+Math.random().toString(36).substring(2),m=JSON.stringify({file:{displayName:s}}),d=Buffer.concat([Buffer.from(`--${p}\r
|
|
184
338
|
Content-Type: application/json\r
|
|
185
339
|
\r
|
|
186
340
|
${m}\r
|
|
187
341
|
`),Buffer.from(`--${p}\r
|
|
188
|
-
Content-Type: ${
|
|
342
|
+
Content-Type: ${i}\r
|
|
189
343
|
\r
|
|
190
|
-
`),
|
|
344
|
+
`),r,Buffer.from(`\r
|
|
191
345
|
--${p}--\r
|
|
192
|
-
`)]),
|
|
346
|
+
`)]),g=await fetch(l,{method:"POST",headers:{"Content-Type":`multipart/related; boundary=${p}`},body:d});if(!g.ok){let b=await g.text();throw new Error(`Gemini file upload failed: ${g.status} ${b}`)}let w=await g.json();return{id:w.file?.name||w.name,url:w.file?.uri||w.uri}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{let t=this.genAI.apiKey,o=`https://generativelanguage.googleapis.com/v1beta/${e}?key=${t}`,r=await fetch(o,{method:"DELETE"});if(!r.ok){let s=await r.text();throw new Error(`Gemini file deletion failed: ${r.status} ${s}`)}}catch(t){throw this.handleError(t)}}getDisplayName(){return"Google Gemini"}async getModels(){return[{id:"gemini-3.1-flash-lite-preview",displayName:"Gemini 3.1 Flash-Lite Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3-flash-preview",displayName:"Gemini 3 Flash Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536},{id:"gemini-3.1-pro-preview",displayName:"Gemini 3.1 Pro Preview",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1048576,maxOutputTokens:65536}]}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,o={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0?(o.tools=[{functionDeclarations:e.tools.map(g=>({name:this.sanitizeToolName(g.function.name),description:g.function.description,parameters:this.sanitizeSchema(g.function.parameters)}))}],y(`[Gemini][${t}] Sending ${e.tools.length} tools`),e.tools.length>0&&y(`[Gemini][${t}] First tool: ${O(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}`),se(t,"Gemini",e.messages);let r=this.genAI.getGenerativeModel(o),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),p=await(await r.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessage(i)).response,m=[],d="";for(let g of p.candidates||[])for(let w of g.content?.parts||[])if(w.text&&(d+=w.text),w.functionCall){let b=w.functionCall;m.push({id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(b.name,e.tools),arguments:b.args||{}})}return y(`[Gemini][${t}] Response finish_reason=${m.length>0?"tool_calls":"stop"} tool_calls=${m.length} content_preview=${O(d,200)}`),{content:d||null,usage:{prompt_tokens:p.usageMetadata?.promptTokenCount||0,completion_tokens:p.usageMetadata?.candidatesTokenCount||0,total_tokens:p.usageMetadata?.totalTokenCount||0},finish_reason:m.length>0?"tool_calls":"stop",tool_calls:m.length>0?m:void 0,raw:p}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t={model:e.model,systemInstruction:this.extractSystemInstruction(e.messages)};e.tools&&e.tools.length>0&&(t.tools=[{functionDeclarations:e.tools.map(p=>({name:this.sanitizeToolName(p.function.name),description:p.function.description,parameters:this.sanitizeSchema(p.function.parameters)}))}]);let o=e.__toolpack_request_id||`str-${Date.now()}`;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: ${O(e.tools[0],800)}`),se(o,"Gemini",e.messages);let r=this.genAI.getGenerativeModel(t),{history:s,lastUserMessage:i}=await this.formatHistory(e.messages,e.mediaOptions),l=await r.startChat({history:s,generationConfig:{maxOutputTokens:e.max_tokens,temperature:e.temperature,topP:e.top_p,responseMimeType:e.response_format==="json_object"?"application/json":"text/plain"}}).sendMessageStream(i);for await(let p of l.stream){for(let m of p.candidates?.[0]?.content?.parts||[])m.functionCall?(y(`[Gemini][${o}] Stream finish_reason=tool_calls name=${m.functionCall.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:[{id:`gemini_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.functionCall.name,e.tools),arguments:m.functionCall.args||{}}]}):m.text&&(yield{delta:m.text});try{let m=p.text();m&&!p.candidates?.[0]?.content?.parts?.some(d=>d.text)&&(yield{delta:m})}catch{}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=this.genAI.getGenerativeModel({model:e.model});return Array.isArray(e.input)?{embeddings:await Promise.all(e.input.map(async r=>(await t.embedContent(r)).embedding.values))}:{embeddings:[(await t.embedContent(e.input)).embedding.values]}}catch(t){throw this.handleError(t)}}extractSystemInstruction(e){let t=e.filter(o=>o.role==="system");if(t.length!==0)return t.map(o=>typeof o.content=="string"?o.content:o.content===null?"":o.content.map(r=>r.text).join(`
|
|
193
347
|
`)).join(`
|
|
194
|
-
`)}async formatHistory(e,t={}){let
|
|
195
|
-
`);
|
|
196
|
-
`);
|
|
197
|
-
Available models: ${e.map(
|
|
198
|
-
`;else if(
|
|
199
|
-
`:
|
|
200
|
-
`}r=r.trim()}let a={role:e.role,content:r};return o.length>0&&(a.images=o),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?a.tool_calls=e.tool_calls.map(i=>({function:{name:this.sanitizeToolName(i.function.name),arguments:typeof i.function.arguments=="string"?JSON.parse(i.function.arguments||"{}"):i.function.arguments}})):e.role==="tool"&&(a.content=r||JSON.stringify(e.content),e.name&&(a.tool_name=this.sanitizeToolName(e.name))),a}handleHttpError(e,t){let r=`Ollama error (HTTP ${e})`;try{let o=JSON.parse(t);o.error&&(r=`Ollama: ${o.error}`)}catch{}return e===404?new M(`Model not found: ${r}`):new F(r,"OLLAMA_ERROR",e)}};l();var lt=class extends Y{baseUrl;timeout;adapterCache=new Map;capabilityCache=new Map;constructor(e){super(),this.baseUrl=e?.baseUrl||"http://localhost:11434",this.timeout=12e4}getDisplayName(){return"Ollama"}async getModels(){let e;try{let t=await ne(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:r,tool_choice:o,...n}=e,a=n,i={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 a.messages=[...a.messages,i],a}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new De({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,r=!1,o=!1;try{let i=await ne(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(i.status===200){let p=(JSON.parse(i.body).details?.families||[]).map(m=>m.toLowerCase());r=p.some(m=>["clip","mllama"].includes(m)),o=p.some(m=>m.includes("bert")||m.includes("nomic"))}}catch{}t=await this.probeToolSupport(e.name);let n=e.name.toLowerCase();r||(r=["llava","vision","bakllava","moondream"].some(c=>n.includes(c))),o||(o=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(c=>n.includes(c)));let a={toolCalling:t,vision:r,embeddings:o};return this.capabilityCache.set(e.name,a),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:o,vision:r}}}async probeToolSupport(e){try{let t=await ne(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 Nr=[{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 gg(){return Nr[0].model}function hg(s){let e=s.toLowerCase();return Nr.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function yg(){return[...Nr]}l();import ks from"openai";ce();k();var po=class extends Y{client;constructor(e,t){super(),this.client=new ks({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()}`,o={messages:await Promise.all(e.messages.map(f=>this.toOpenAIMessage(f,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!1},n=new Map;e.tools&&e.tools.length>0&&(o.tools=e.tools.map(f=>{let h=this.sanitizeToolName(f.function.name);return n.set(h,f.function.name),{type:"function",function:{name:h,description:f.function.description,parameters:f.function.parameters}}}),o.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${o.tools.length} tools with tool_choice: ${o.tool_choice}`),y(`[OpenAI][${t}] First tool: ${D(o.tools[0],800)}`)),y(`[OpenAI][${t}] Request params: ${D({model:o.model,messages_count:o.messages.length,has_tools:!!o.tools,tools_count:o.tools?.length,tool_choice:o.tool_choice},800)}`),V(t,"OpenAI",o.messages);let a=await this.client.chat.completions.create(o,e.signal?{signal:e.signal}:void 0);ye(`[OpenAI][${t}] Raw completion: ${JSON.stringify(a)}`);let i=a.choices[0].message;y(`[OpenAI][${t}] Response: finish_reason=${a.choices[0].finish_reason}`),y(`[OpenAI][${t}] Response has tool_calls: ${!!i.tool_calls}, count: ${i.tool_calls?.length||0}`),y(`[OpenAI][${t}] Response content: ${JSON.stringify(i.content)}`),i.content&&y(`[OpenAI][${t}] Response content preview: ${D(i.content,200)}`);let c=a.choices[0],p,m=c.message.tool_calls;return m&&m.length>0&&(p=m.map(f=>({id:f.id,name:n.get(f.function.name)||f.function.name,arguments:JSON.parse(f.function.arguments)}))),{content:c.message.content,usage:a.usage?{prompt_tokens:a.usage.prompt_tokens,completion_tokens:a.usage.completion_tokens,total_tokens:a.usage.total_tokens}:void 0,finish_reason:c.finish_reason,tool_calls:p,raw:a}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,o={messages:await Promise.all(e.messages.map(c=>this.toOpenAIMessage(c,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!0},n=new Map;e.tools&&e.tools.length>0?(o.tools=e.tools.map(c=>{let p=this.sanitizeToolName(c.function.name);return n.set(p,c.function.name),{type:"function",function:{name:p,description:c.function.description,parameters:c.function.parameters}}}),o.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${o.tools.length} tools with tool_choice: ${o.tool_choice}`),y(`[OpenAI][${t}] First tool: ${D(o.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${o.model}, messages=${o.messages.length}, tools=${o.tools?.length||0}, tool_choice=${o.tool_choice??"unset"}`),V(t,"OpenAI",o.messages);let a=await this.client.chat.completions.create(o,e.signal?{signal:e.signal}:void 0),i=new Map;for await(let c of a){let p=c.choices[0];if(p.finish_reason&&ye(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let f=m.index;i.has(f)||i.set(f,{id:m.id||"",name:m.function?.name||"",args:""});let h=i.get(f);m.id&&(h.id=m.id),m.function?.name&&(h.name=m.function.name),m.function?.arguments&&(h.args+=m.function.arguments),ye(`[OpenAI][${t}] tool_call_delta idx=${f} id=${m.id||h.id||""} name=${m.function?.name||h.name||""} args_delta=${D(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:c.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:c.usage}),p.finish_reason==="tool_calls"&&i.size>0){let m=Array.from(i.values()).map(f=>({id:f.id,name:n.get(f.name)||f.name,arguments:JSON.parse(f.args||"{}")}));y(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(f=>f.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,r=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:r.data.map(o=>o.embedding),usage:r.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(n=>({id:n.id,type:"function",function:{name:this.sanitizeToolName(n.function.name),arguments:n.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:r}=await Promise.resolve().then(()=>(Ue(),st)),o=await Promise.all(e.content.map(async n=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="image_url")return{type:"image_url",image_url:{url:n.image_url.url}};if(n.type==="image_data"||n.type==="image_file"){let{data:a,mimeType:i}=await r(n);return{type:"image_url",image_url:{url:`data:${i};base64,${a}`}}}return null}));return{role:e.role,content:o.filter(Boolean)}}handleError(e){if(e instanceof ks.APIError){let t=e.message;return e.status===401?new ge(t,e):e.status===429?new he(t,void 0,e):e.status&&e.status>=400&&e.status<500?new M(t,e):new F(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new F("Unknown error","UNKNOWN",500,e)}};Ue();l();rt();l();rt();var Vt=class{tools=new Map;projects=new Map;config=z;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),r=new Set,o=[];for(let n of[...e,...t])r.has(n.name)||(r.add(n.name),o.push(n));return o}getSchemas(e){return(e?e.map(r=>this.tools.get(r)).filter(Boolean):this.getEnabled()).map(r=>({name:r.name,displayName:r.displayName,description:r.description,parameters:r.parameters,category:r.category}))}getByNames(e){return e.map(t=>this.tools.get(t)).filter(Boolean)}getByCategories(e){let t=new Set(e);return Array.from(this.tools.values()).filter(r=>t.has(r.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 r=[];for(let o of Object.keys(t))try{await import(o)}catch{r.push(o)}return r}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 r of e.tools)this.register(r)}async loadProjects(e){for(let t of e)await this.loadProject(t)}getProject(e){return this.projects.get(e)}getProjects(){return Array.from(this.projects.values())}getProjectNames(){return Array.from(this.projects.keys())}async loadBuiltIn(){let{fsToolsProject:e}=await Promise.resolve().then(()=>(Vr(),Wa)),{execToolsProject:t}=await Promise.resolve().then(()=>(nn(),Rl)),{systemToolsProject:r}=await Promise.resolve().then(()=>(dn(),pc)),{httpToolsProject:o}=await Promise.resolve().then(()=>(wn(),zc)),{webToolsProject:n}=await Promise.resolve().then(()=>(Dn(),gm)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Kn(),eu)),{gitToolsProject:i}=await Promise.resolve().then(()=>(Qn(),Ru)),{diffToolsProject:c}=await Promise.resolve().then(()=>(Yn(),Bu)),{dbToolsProject:p}=await Promise.resolve().then(()=>(Xn(),wf)),{cloudToolsProject:m}=await Promise.resolve().then(()=>(Zn(),Rf));await this.loadProjects([e,t,r,o,n,a,i,c,p,m])}};Tn();l();k();function zy(s){if(!s.key||!/^[a-z0-9-]+$/.test(s.key))throw new Error(`Invalid tool project key: "${s.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!s.name.trim())throw new Error("Tool project name cannot be empty.");if(!s.tools||s.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of s.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!==s.category&&E(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${s.category}".`)}let e=s.tools.map(t=>t.name);return{manifest:{key:s.key,name:s.name,displayName:s.displayName,version:s.version,description:s.description,author:s.author,repository:s.repository,category:s.category,tools:e},dependencies:s.dependencies,tools:s.tools}}Vr();nn();dn();wn();Dn();Kn();Qn();Yn();Xn();Zn();l();l();k();import{spawn as Ky}from"child_process";import{EventEmitter as Qy}from"events";var hr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},me=class extends Error{constructor(t,r){super(t);this.exitCode=r;this.name="McpConnectionError"}exitCode},Xt=class extends Qy{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 connect(){if(this._shuttingDown)throw new me("Client is shutting down");return new Promise((t,r)=>{try{if(this.buffer="",this.process=Ky(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new me("Failed to spawn MCP server: stdout/stdin unavailable");this.process.stdout.on("data",o=>{this.handleData(o)}),this.process.stderr&&this.process.stderr.on("data",o=>{E(`[MCP server stderr] ${o.toString().trim()}`)}),this.process.on("error",o=>{this._connected=!1,this.emit("error",o)}),this.process.on("exit",o=>{let n=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new me(`MCP server exited with code ${o}`,o)),this.emit("close",o),n&&!this._shuttingDown&&this.autoReconnect&&this.attemptReconnect()}),this._connected=!0,this._reconnectAttempts=0,setTimeout(t,500)}catch(o){r(o)}})}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(r=>setTimeout(r,this.reconnectDelayMs*t)),!this._shuttingDown)try{await this.connect(),this.emit("reconnected",{attempt:t})}catch(r){this.emit("reconnect_error",{attempt:t,error:r})}}handleData(t){this.buffer+=t.toString();let r;for(;(r=this.buffer.indexOf(`
|
|
201
|
-
`)
|
|
202
|
-
|
|
348
|
+
`)}async formatHistory(e,t={}){let o=e.filter(m=>m.role!=="system");if(o.length===0)return{history:[],lastUserMessage:""};let r=o[o.length-1],s=o.slice(0,o.length-1),{normalizeImagePart:i}=await Promise.resolve().then(()=>(tt(),St)),a=async m=>typeof m=="string"?[{text:m}]:m===null?[]:(await Promise.all(m.map(async g=>{if(g.type==="text")return{text:g.text};if(g.type==="image_data"||g.type==="image_file"||g.type==="image_url")try{let{data:w,mimeType:b}=await i(g);return{inlineData:{mimeType:b,data:w}}}catch{return g.type==="image_url"?{text:`[Image: ${g.image_url.url}]`}:{text:"[Unresolvable Image]"}}return null}))).filter(Boolean),l=await Promise.all(s.map(async m=>{if(m.role==="tool"&&m.tool_call_id)return{role:"function",parts:[{functionResponse:{name:this.sanitizeToolName(m.name||m.tool_call_id),response:{name:this.sanitizeToolName(m.name||m.tool_call_id),content:typeof m.content=="string"?m.content:JSON.stringify(m.content)}}}]};if(m.role==="assistant"&&m.tool_calls&&m.tool_calls.length>0){let d=[];if(typeof m.content=="string"&&m.content)d.push({text:m.content});else if(Array.isArray(m.content)){let g=m.content.filter(w=>typeof w=="object"&&w.type==="text").map(w=>w.text).join(`
|
|
349
|
+
`);g&&d.push({text:g})}for(let g of m.tool_calls)d.push({functionCall:{name:this.sanitizeToolName(g.function.name),args:typeof g.function.arguments=="string"?JSON.parse(g.function.arguments||"{}"):g.function.arguments}});return{role:"model",parts:d}}return{role:m.role==="user"?"user":"model",parts:await a(m.content)}})),p=typeof r.content=="string"?r.content:await a(r.content);return{history:l,lastUserMessage:p}}handleError(e){return e.status===429?new ke(e.message,void 0,e):e.status>=400&&e.status<500?new j(e.message,e):e.message&&e.message.includes("API key")?new Se(e.message,e):new W(e.message||"Gemini Error","GEMINI_ERROR",e.status||500,e)}};c();ne();import*as _e from"fs";import*as fn from"path";var Ki="toolpack.config.json",jo=new Map;async function Ji(n){for(;jo.has(n);)await jo.get(n);let e,t=new Promise(o=>{e=o});return jo.set(n,t),()=>{jo.delete(n),e()}}function Ge(n){if(n&&_e.existsSync(n))return n;let e=fn.join(process.cwd(),Ki);return _e.existsSync(e)?e:null}function Rt(n){if(!n)return null;try{let e=_e.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}var kt=null;function gn(n){if(kt)return kt;let e=n||Ge();return kt=Rt(e)||{},kt}function hn(){kt=null}function Yy(n){return(gn(n).ollama?.models||[]).map(o=>({type:`ollama-${o.model.replace(/[:.]/g,"-")}`,model:o.model,label:o.label||o.model}))}function Fo(n){return gn(n).ollama?.baseUrl||"http://localhost:11434"}async function Zy(n){let{type:e,value:t,configPath:o}=n,r=o||Ge();r||(r=fn.join(process.cwd(),Ki));let s=await Ji(r);try{let i=Rt(r)||{};switch(i.hitl||(i.hitl={}),i.hitl.bypass||(i.hitl.bypass={}),e){case"tool":i.hitl.bypass.tools||(i.hitl.bypass.tools=[]),i.hitl.bypass.tools.includes(t)||i.hitl.bypass.tools.push(t);break;case"category":i.hitl.bypass.categories||(i.hitl.bypass.categories=[]),i.hitl.bypass.categories.includes(t)||i.hitl.bypass.categories.push(t);break;case"level":{i.hitl.bypass.levels||(i.hitl.bypass.levels=[]);let a=t;i.hitl.bypass.levels.includes(a)||i.hitl.bypass.levels.push(a);break}}try{_e.writeFileSync(r,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new A(`Failed to write bypass rule to config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}hn()}finally{s()}}async function eb(n){let{type:e,value:t,configPath:o}=n,r=o||Ge();if(!r)return;let s=await Ji(r);try{let i=Rt(r);if(!i?.hitl?.bypass)return;switch(e){case"tool":i.hitl.bypass.tools&&(i.hitl.bypass.tools=i.hitl.bypass.tools.filter(a=>a!==t));break;case"category":i.hitl.bypass.categories&&(i.hitl.bypass.categories=i.hitl.bypass.categories.filter(a=>a!==t));break;case"level":i.hitl.bypass.levels&&(i.hitl.bypass.levels=i.hitl.bypass.levels.filter(a=>a!==t));break}try{_e.writeFileSync(r,JSON.stringify(i,null,4),"utf-8")}catch(a){throw new A(`Failed to remove bypass rule from config file: ${a instanceof Error?a.message:String(a)}`,"CONFIG_WRITE_ERROR")}hn()}finally{s()}}c();c();ne();P();c();import Qi from"http";function ge(n,e,t,o,r=12e4){return new Promise((s,i)=>{let a=new URL(e,n),l={hostname:a.hostname,port:a.port,path:a.pathname,method:t,headers:{"Content-Type":"application/json"},timeout:r},p=Qi.request(l,m=>{let d=[];m.on("data",g=>d.push(g)),m.on("end",()=>{s({status:m.statusCode||0,body:Buffer.concat(d).toString("utf-8")})})});p.on("error",m=>i(m)),p.on("timeout",()=>{p.destroy(),i(new Error("Request timed out"))}),o&&p.write(JSON.stringify(o)),p.end()})}function yn(n,e,t,o=12e4,r){let s,i=!1;return r&&r.addEventListener("abort",()=>{i=!0,s&&s.destroy()},{once:!0}),{stream:async function*(){let l=new URL(e,n),p={hostname:l.hostname,port:l.port,path:l.pathname,method:"POST",headers:{"Content-Type":"application/json"},timeout:o},m=await new Promise((g,w)=>{s=Qi.request(p,g),s.on("error",w),s.on("timeout",()=>{s.destroy(),w(new Error("Stream request timed out"))}),s.write(JSON.stringify(t)),s.end()});if(m.statusCode&&m.statusCode>=400){let g="";for await(let w of m)g+=w.toString();throw new Error(`Ollama HTTP ${m.statusCode}: ${g}`)}let d="";for await(let g of m){if(i)break;let w=g.toString();if(d+=w,d.includes('"error"'))try{let T=JSON.parse(d.trim());if(T.error)throw new Error(`Ollama: ${T.error}`)}catch(T){if(T.message.startsWith("Ollama:"))throw T}let b=d.split(`
|
|
350
|
+
`);d=b.pop()||"";for(let T of b)T.trim()&&(yield T)}d.trim()&&!i&&(yield d.trim())}(),abort:()=>{i=!0,s&&s.destroy()}}}var Be=class extends te{config;baseUrl;timeout;modelName;constructor(e){super(),this.config=e,this.baseUrl=e.baseUrl||"http://localhost:11434",this.timeout=e.timeout||12e4,this.modelName=e.model}getDisplayName(){return"Ollama"}async getModels(){try{return(await this.listModels()).map(t=>({id:t.name,displayName:t.name,capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!0,vision:!0}}))}catch{return[]}}async connect(){let e=await this.listModels(),t=this.config.model.split(":")[0].toLowerCase();if(!e.some(r=>r.name.split(":")[0].toLowerCase()===t||r.name.toLowerCase()===this.config.model.toLowerCase()))throw new j(`Model "${this.config.model}" is not pulled in Ollama. Run: ollama pull ${this.config.model}
|
|
351
|
+
Available models: ${e.map(r=>r.name).join(", ")||"(none)"}`);return e}async listModels(){try{let e=await ge(this.baseUrl,"/api/tags","GET",void 0,5e3);if(e.status!==200)throw new W(`Ollama returned status ${e.status}`,"OLLAMA_ERROR",e.status);return JSON.parse(e.body).models||[]}catch(e){throw e instanceof W?e:new qe(`Cannot connect to Ollama at ${this.baseUrl}. Is Ollama running? (ollama serve)`,e)}}async isAvailable(){try{return await ge(this.baseUrl,"/api/tags","GET",void 0,3e3),!0}catch{return!1}}async isModelAvailable(e){try{let t=await this.listModels(),o=(e||this.config.model).toLowerCase(),r=o.split(":")[0];return t.some(s=>s.name.split(":")[0].toLowerCase()===r||s.name.toLowerCase()===o)}catch{return!1}}sanitizeToolName(e){return e.replace(/\./g,"_")}restoreToolName(e,t){return t?.find(r=>this.sanitizeToolName(r.function.name)===e)?.function.name||e.replace(/_/g,".")}async generate(e){let t=e.__toolpack_request_id||`gen-${Date.now()}`,o=await Promise.all(e.messages.map(i=>this.toOllamaMessage(i,e.mediaOptions))),r=e.model||this.config.model,s={model:r,messages:o,stream:!1,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(i=>({type:"function",function:{name:this.sanitizeToolName(i.function.name),description:i.function.description,parameters:i.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${O(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] generate() request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),se(t,"Ollama",e.messages);try{let i=await ge(this.baseUrl,"/api/chat","POST",s,this.timeout);if(i.status!==200)throw this.handleHttpError(i.status,i.body);let a=JSON.parse(i.body),l=[];if(a.message?.tool_calls)for(let m of a.message.tool_calls)l.push({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}});let p={content:a.message?.content||null,usage:a.prompt_eval_count!=null?{prompt_tokens:a.prompt_eval_count||0,completion_tokens:a.eval_count||0,total_tokens:(a.prompt_eval_count||0)+(a.eval_count||0)}:void 0,finish_reason:l.length>0?"tool_calls":a.done?"stop":void 0,tool_calls:l.length>0?l:void 0,raw:a};return y(`[Ollama][${t}] Response finish_reason=${p.finish_reason} tool_calls=${l.length} content_preview=${O(p.content,200)}`),p}catch(i){throw i instanceof W?i:new qe(`Failed to generate with Ollama model "${r}": ${i.message}`,i)}}async*stream(e){let t=e.__toolpack_request_id||`str-${Date.now()}`,o=await Promise.all(e.messages.map(a=>this.toOllamaMessage(a,e.mediaOptions))),r=e.model||this.config.model,s={model:r,messages:o,stream:!0,options:{temperature:e.temperature??this.config.temperature??.7,num_ctx:this.config.numCtx}};e.tools&&e.tools.length>0&&e.tool_choice!=="none"&&(s.tools=e.tools.map(a=>({type:"function",function:{name:this.sanitizeToolName(a.function.name),description:a.function.description,parameters:a.function.parameters}})),y(`[Ollama][${t}] Sending ${e.tools.length} tools with tool_choice: ${e.tool_choice||"unset"}`),e.tools.length>0&&y(`[Ollama][${t}] First tool: ${O(e.tools[0],800)}`),y(`[Ollama][${t}] NO TOOLS in request`)),y(`[Ollama][${t}] Stream request: model=${r}, messages=${e.messages.length}, tools=${e.tools?.length||0}`),se(t,"Ollama",e.messages);let{stream:i}=yn(this.baseUrl,"/api/chat",s,this.timeout,e.signal);try{for await(let a of i)try{let l=JSON.parse(a);if(l.message?.content){let p=l.message.tool_calls&&l.message.tool_calls.length>0;yield{delta:l.message.content,finish_reason:l.done&&!p?"stop":void 0,usage:l.done&&l.prompt_eval_count!=null?{prompt_tokens:l.prompt_eval_count||0,completion_tokens:l.eval_count||0,total_tokens:(l.prompt_eval_count||0)+(l.eval_count||0)}:void 0}}if(l.message?.tool_calls&&l.message.tool_calls.length>0){let p=l.message.tool_calls.map(m=>({id:`ollama_${Date.now()}_${Math.random().toString(36).substring(2,8)}`,name:this.restoreToolName(m.function.name,e.tools),arguments:m.function.arguments||{}}));y(`[Ollama][${t}] Stream finish_reason=tool_calls name=${p[0]?.name}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:p}}if(l.done&&!l.message?.content&&!l.message?.tool_calls){$e(`[Ollama][${t}] Stream chunk finish_reason=stop`),yield{delta:"",finish_reason:"stop"};return}}catch{}}catch(a){throw new qe(`Stream failed for Ollama model "${r}": ${a.message}`,a)}}async embed(e){let t=e.__toolpack_request_id||`emb-${Date.now()}`,o=typeof e.input=="string"?[e.input]:e.input,r=e.model||this.config.model;y(`[Ollama][${t}] Embedding request: model=${r}, inputs=${o.length}`);try{let s=await ge(this.baseUrl,"/api/embed","POST",{model:r,input:o},this.timeout);if(s.status!==200)throw this.handleHttpError(s.status,s.body);return{embeddings:JSON.parse(s.body).embeddings||[]}}catch(s){throw s instanceof W?s:new qe(`Embedding failed for Ollama model "${r}": ${s.message}`,s)}}async disconnect(){}async toOllamaMessage(e,t={}){let o="",r=[],{normalizeImagePart:s}=await Promise.resolve().then(()=>(tt(),St));if(typeof e.content=="string")o=e.content;else if(e.content!==null){for(let a of e.content)if(a.type==="text")o+=a.text+`
|
|
352
|
+
`;else if(a.type==="image_url"||a.type==="image_data"||a.type==="image_file")try{let{data:l}=await s(a);r.push(l)}catch{a.type==="image_url"?o+=`[Image: ${a.image_url.url}]
|
|
353
|
+
`:o+=`[Unresolvable Image]
|
|
354
|
+
`}o=o.trim()}let i={role:e.role,content:o};return r.length>0&&(i.images=r),e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0?i.tool_calls=e.tool_calls.map(a=>({function:{name:this.sanitizeToolName(a.function.name),arguments:typeof a.function.arguments=="string"?JSON.parse(a.function.arguments||"{}"):a.function.arguments}})):e.role==="tool"&&(i.content=o||JSON.stringify(e.content),e.name&&(i.tool_name=this.sanitizeToolName(e.name))),i}handleHttpError(e,t){let o=`Ollama error (HTTP ${e})`;try{let r=JSON.parse(t);r.error&&(o=`Ollama: ${r.error}`)}catch{}return e===404?new j(`Model not found: ${o}`):new W(o,"OLLAMA_ERROR",e)}};c();var $t=class extends te{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 ge(this.baseUrl,"/api/tags","GET",void 0,5e3);if(t.status!==200)return[];e=JSON.parse(t.body).models||[]}catch{return[]}return Promise.all(e.map(t=>this.buildModelInfo(t)))}async generate(e){return this.getAdapterForModel(e.model).generate(this.stripToolsIfNeeded(e))}async*stream(e){yield*this.getAdapterForModel(e.model).stream(this.stripToolsIfNeeded(e))}async embed(e){return this.getAdapterForModel(e.model).embed(e)}async disconnect(){this.adapterCache.clear(),this.capabilityCache.clear()}stripToolsIfNeeded(e){let t=this.capabilityCache.get(e.model);if(t&&!t.toolCalling&&e.tools&&e.tools.length>0){let{tools:o,tool_choice:r,...s}=e,i=s,a={role:"system",content:"You do not have access to any tools or functions. Do not attempt to call tools, output tool invocations, or reference tool usage. Answer the user directly using only your own knowledge."};return i.messages=[...i.messages,a],i}return e}getAdapterForModel(e){let t=this.adapterCache.get(e);return t||(t=new Be({model:e,baseUrl:this.baseUrl,timeout:this.timeout}),this.adapterCache.set(e,t)),t}async buildModelInfo(e){let t=!1,o=!1,r=!1;try{let a=await ge(this.baseUrl,"/api/show","POST",{model:e.name},3e3);if(a.status===200){let p=(JSON.parse(a.body).details?.families||[]).map(m=>m.toLowerCase());o=p.some(m=>["clip","mllama"].includes(m)),r=p.some(m=>m.includes("bert")||m.includes("nomic"))}}catch{}t=await this.probeToolSupport(e.name);let s=e.name.toLowerCase();o||(o=["llava","vision","bakllava","moondream"].some(l=>s.includes(l))),r||(r=["nomic-embed","mxbai-embed","all-minilm","bge-","snowflake-arctic-embed"].some(l=>s.includes(l)));let i={toolCalling:t,vision:o,embeddings:r};return this.capabilityCache.set(e.name,i),{id:e.name,displayName:e.name,capabilities:{chat:!0,streaming:!0,toolCalling:t,embeddings:r,vision:o}}}async probeToolSupport(e){try{let t=await ge(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 bn=[{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 tb(){return bn[0].model}function ob(n){let e=n.toLowerCase();return bn.some(t=>t.model.toLowerCase()===e||t.model.split(":")[0].toLowerCase()===e.split(":")[0].toLowerCase())}function rb(){return[...bn]}c();import Vi from"openai";ne();P();var ot=class extends te{client;constructor(e,t){super(),this.client=new Vi({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 j("OpenAI uploadFile requires a filePath.");return{id:(await this.client.files.create({file:t.createReadStream(e.filePath),purpose:e.purpose||"vision"})).id}}catch(t){throw this.handleError(t)}}async deleteFile(e){try{await this.client.files.delete(e)}catch(t){throw this.handleError(t)}}getDisplayName(){return"OpenAI"}async getModels(){return[{id:"gpt-4.1-mini",displayName:"GPT-4.1 Mini",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"low"},{id:"gpt-4.1",displayName:"GPT-4.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:1047576,maxOutputTokens:32768,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:null,costTier:"medium"},{id:"gpt-5.1",displayName:"GPT-5.1",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"medium"},{id:"gpt-5.2",displayName:"GPT-5.2",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:4e5,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4",displayName:"GPT-5.4",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"standard",costTier:"high"},{id:"gpt-5.4-pro",displayName:"GPT-5.4 Pro",capabilities:{chat:!0,streaming:!0,toolCalling:!0,embeddings:!1,vision:!0,fileUpload:!0},contextWindow:105e4,maxOutputTokens:128e3,inputModalities:["text","image"],outputModalities:["text"],reasoningTier:"extended",costTier:"premium"}]}sanitizeToolName(e){return e.replace(/\./g,"_")}async generate(e){try{let t=e.__toolpack_request_id||`gen-${Date.now()}`,r={messages:await Promise.all(e.messages.map(d=>this.toOpenAIMessage(d,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!1},s=new Map;e.tools&&e.tools.length>0&&(r.tools=e.tools.map(d=>{let g=this.sanitizeToolName(d.function.name);return s.set(g,d.function.name),{type:"function",function:{name:g,description:d.function.description,parameters:d.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),y(`[OpenAI][${t}] First tool: ${O(r.tools[0],800)}`)),y(`[OpenAI][${t}] Request params: ${O({model:r.model,messages_count:r.messages.length,has_tools:!!r.tools,tools_count:r.tools?.length,tool_choice:r.tool_choice},800)}`),se(t,"OpenAI",r.messages);let i=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0);$e(`[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: ${O(a.content,200)}`);let l=i.choices[0],p,m=l.message.tool_calls;return m&&m.length>0&&(p=m.map(d=>({id:d.id,name:s.get(d.function.name)||d.function.name,arguments:JSON.parse(d.function.arguments)}))),{content:l.message.content,usage:i.usage?{prompt_tokens:i.usage.prompt_tokens,completion_tokens:i.usage.completion_tokens,total_tokens:i.usage.total_tokens}:void 0,finish_reason:l.finish_reason,tool_calls:p,raw:i}}catch(t){throw this.handleError(t)}}async*stream(e){try{let t=e.__toolpack_request_id||`str-${Date.now()}`,r={messages:await Promise.all(e.messages.map(l=>this.toOpenAIMessage(l,e.mediaOptions))),model:e.model,temperature:e.temperature,max_tokens:e.max_tokens,top_p:e.top_p,response_format:e.response_format==="json_object"?{type:"json_object"}:void 0,stream:!0},s=new Map;e.tools&&e.tools.length>0?(r.tools=e.tools.map(l=>{let p=this.sanitizeToolName(l.function.name);return s.set(p,l.function.name),{type:"function",function:{name:p,description:l.function.description,parameters:l.function.parameters}}}),r.tool_choice=e.tool_choice||"auto",y(`[OpenAI][${t}] Sending ${r.tools.length} tools with tool_choice: ${r.tool_choice}`),y(`[OpenAI][${t}] First tool: ${O(r.tools[0],800)}`)):y(`[OpenAI][${t}] NO TOOLS in request`),y(`[OpenAI][${t}] Stream request: model=${r.model}, messages=${r.messages.length}, tools=${r.tools?.length||0}, tool_choice=${r.tool_choice??"unset"}`),se(t,"OpenAI",r.messages);let i=await this.client.chat.completions.create(r,e.signal?{signal:e.signal}:void 0),a=new Map;for await(let l of i){let p=l.choices[0];if(p.finish_reason&&$e(`[OpenAI][${t}] Stream chunk finish_reason=${p.finish_reason}`),p.delta.tool_calls)for(let m of p.delta.tool_calls){let d=m.index;a.has(d)||a.set(d,{id:m.id||"",name:m.function?.name||"",args:""});let g=a.get(d);m.id&&(g.id=m.id),m.function?.name&&(g.name=m.function.name),m.function?.arguments&&(g.args+=m.function.arguments),$e(`[OpenAI][${t}] tool_call_delta idx=${d} id=${m.id||g.id||""} name=${m.function?.name||g.name||""} args_delta=${O(m.function?.arguments||"",200)}`)}if(p.delta.content&&(yield{delta:p.delta.content,finish_reason:p.finish_reason,usage:l.usage}),!p.delta.content&&p.finish_reason&&p.finish_reason!=="tool_calls"&&(yield{delta:"",finish_reason:p.finish_reason,usage:l.usage}),p.finish_reason==="tool_calls"&&a.size>0){let m=Array.from(a.values()).map(d=>({id:d.id,name:s.get(d.name)||d.name,arguments:JSON.parse(d.args||"{}")}));y(`[OpenAI][${t}] Stream finish_reason=tool_calls accumulated_calls=${m.length} names=${m.map(d=>d.name).join(", ")}`),yield{delta:"",finish_reason:"tool_calls",tool_calls:m}}}}catch(t){throw this.handleError(t)}}async embed(e){try{let t=typeof e.input=="string"?[e.input]:e.input,o=await this.client.embeddings.create({model:e.model,input:t});return{embeddings:o.data.map(r=>r.embedding),usage:o.usage}}catch(t){throw this.handleError(t)}}async toOpenAIMessage(e,t={}){if(e.role==="tool"&&e.tool_call_id)return{role:"tool",tool_call_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content??"")};if(e.role==="assistant"&&e.tool_calls&&e.tool_calls.length>0)return{role:"assistant",content:typeof e.content=="string"?e.content:"",tool_calls:e.tool_calls.map(s=>({id:s.id,type:"function",function:{name:this.sanitizeToolName(s.function.name),arguments:s.function.arguments}}))};if(typeof e.content=="string")return{role:e.role,content:e.content};if(e.content===null||e.content===void 0)return{role:e.role,content:""};let{normalizeImagePart:o}=await Promise.resolve().then(()=>(tt(),St)),r=await Promise.all(e.content.map(async s=>{if(s.type==="text")return{type:"text",text:s.text};if(s.type==="image_url")return{type:"image_url",image_url:{url:s.image_url.url}};if(s.type==="image_data"||s.type==="image_file"){let{data:i,mimeType:a}=await o(s);return{type:"image_url",image_url:{url:`data:${a};base64,${i}`}}}return null}));return{role:e.role,content:r.filter(Boolean)}}handleError(e){if(e instanceof Vi.APIError){let t=e.message;return e.status===401?new Se(t,e):e.status===429?new ke(t,void 0,e):e.status&&e.status>=400&&e.status<500?new j(t,e):new W(t,e.code||"OPENAI_ERROR",e.status||500,e)}return new W("Unknown error","UNKNOWN",500,e)}};c();var Xi="https://openrouter.ai/api/v1",qo=class extends ot{name="openrouter";_apiKey;constructor(e,t={}){super(e,Xi),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(`${Xi}/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"}};tt();c();vt();c();vt();var ko=class{tools=new Map;projects=new Map;config=Y;register(e){this.tools.set(e.name,e)}registerCustom(e){this.tools.set(e.name,e)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getNames(){return Array.from(this.tools.keys())}getByCategory(e){return Array.from(this.tools.values()).filter(t=>t.category===e)}getEnabled(){if(this.config.enabledTools.length===0&&this.config.enabledToolCategories.length===0)return Array.from(this.tools.values());let e=this.getByNames(this.config.enabledTools),t=this.getByCategories(this.config.enabledToolCategories),o=new Set,r=[];for(let s of[...e,...t])o.has(s.name)||(o.add(s.name),r.push(s));return r}getSchemas(e){return(e?e.map(o=>this.tools.get(o)).filter(Boolean):this.getEnabled()).map(o=>({name:o.name,displayName:o.displayName,description:o.description,parameters:o.parameters,category:o.category}))}getByNames(e){return e.map(t=>this.tools.get(t)).filter(Boolean)}getByCategories(e){let t=new Set(e);return Array.from(this.tools.values()).filter(o=>t.has(o.category))}getCategories(){let e=new Set;for(let t of this.tools.values())e.add(t.category);return Array.from(e)}getAll(){return Array.from(this.tools.values())}setConfig(e){this.config=e}getConfig(){return this.config}get size(){return this.tools.size}async validateDependencies(e){let t=e.dependencies;if(!t||Object.keys(t).length===0)return[];let o=[];for(let r of Object.keys(t))try{await import(r)}catch{o.push(r)}return o}async loadProject(e){let t=await this.validateDependencies(e);if(t.length>0)throw new Error(`Tool project "${e.manifest.name}" has missing dependencies: ${t.join(", ")}. Install them with: npm install ${t.join(" ")}`);this.projects.set(e.manifest.name,e);for(let o of e.tools)this.register(o)}async loadProjects(e){for(let t of e)await this.loadProject(t)}getProject(e){return this.projects.get(e)}getProjects(){return Array.from(this.projects.values())}getProjectNames(){return Array.from(this.projects.keys())}async loadBuiltIn(){let{fsToolsProject:e}=await Promise.resolve().then(()=>(Ln(),mc)),{execToolsProject:t}=await Promise.resolve().then(()=>(Bn(),Yc)),{systemToolsProject:o}=await Promise.resolve().then(()=>(Xn(),Np)),{httpToolsProject:r}=await Promise.resolve().then(()=>(rs(),hm)),{githubToolsProject:s}=await Promise.resolve().then(()=>(fs(),vd)),{webToolsProject:i}=await Promise.resolve().then(()=>(Rs(),Bu)),{codingToolsProject:a}=await Promise.resolve().then(()=>(Bs(),Eg)),{gitToolsProject:l}=await Promise.resolve().then(()=>(zs(),sh)),{diffToolsProject:p}=await Promise.resolve().then(()=>(Hs(),Th)),{dbToolsProject:m}=await Promise.resolve().then(()=>(Js(),Kh)),{cloudToolsProject:d}=await Promise.resolve().then(()=>(Qs(),ny));await this.loadProjects([e,t,o,r,s,i,a,l,p,m,d])}};ys();c();P();function BT(n){if(!n.key||!/^[a-z0-9-]+$/.test(n.key))throw new Error(`Invalid tool project key: "${n.key}". Must be non-empty, lowercase, and contain no spaces (use hyphens).`);if(!n.name.trim())throw new Error("Tool project name cannot be empty.");if(!n.tools||n.tools.length===0)throw new Error("Tool project must contain at least one tool.");for(let t of n.tools){if(!t.name)throw new Error("Tool is missing a name.");if(!t.description)throw new Error(`Tool "${t.name}" is missing a description.`);if(!t.parameters)throw new Error(`Tool "${t.name}" is missing parameters.`);if(typeof t.execute!="function")throw new Error(`Tool "${t.name}" is missing an execute function.`);t.category!==n.category&&M(`[Toolpack] Tool "${t.name}" has category "${t.category}" which does not match project category "${n.category}".`)}let e=n.tools.map(t=>t.name);return{manifest:{key:n.key,name:n.name,displayName:n.displayName,version:n.version,description:n.description,author:n.author,repository:n.repository,category:n.category,tools:e},dependencies:n.dependencies,tools:n.tools}}Ln();Bn();Xn();rs();fs();Rs();Bs();zs();Hs();Js();Qs();c();c();P();import{execFileSync as zT}from"child_process";function N(n,e){if(n.includes("\0")||n.includes(`
|
|
355
|
+
`)||n.includes("\r"))throw new Error(`Invalid ${e}: contains disallowed characters.`);return n}function HT(n){let e=typeof n.stdout=="string"?n.stdout:"",t=typeof n.stderr=="string"?n.stderr:"",o=n.status??"unknown",r=t.split(/\r?\n/).filter(i=>i.trim().length>0),s=r.find(i=>i.toLowerCase().startsWith("error:"))||r[0]||n.message||"";return`kubectl failed (exit code ${o})${s?`: ${s.trim()}`:""}
|
|
356
|
+
STDOUT:
|
|
357
|
+
${e}
|
|
358
|
+
STDERR:
|
|
359
|
+
${t}`}function oe(n,e,t=3e4){n.forEach((o,r)=>N(o,`kubectl argument #${r}`)),y(`[k8s-tools] execute: kubectl ${n.join(" ")}`);try{return zT("kubectl",n,{input:e,encoding:"utf-8",maxBuffer:10485760,stdio:["pipe","pipe","pipe"],timeout:t})||"(kubectl completed with no output)"}catch(o){return HT(o)}}function KT(n){if(!n)return 3e5;let e=n.trim().toLowerCase(),t=/^([0-9]+)(s|m|h)?$/.exec(e);if(!t)return 3e5;let o=Number(t[1]);switch(t[2]){case"h":return o*60*60*1e3;case"m":return o*60*1e3;default:return o*1e3}}var ue="kubernetes";function sy(n){if(!n)return;if(typeof n=="string")return n;let e=Object.entries(n).filter(([,t])=>t!==void 0&&t!=="");if(e.length)return e.map(([t,o])=>`${N(t,"label key")}=${N(o,"label value")}`).join(",")}var Vs={name:"k8s.list_pods",displayName:"Kubernetes List Pods",description:"List pods in the current or a specific Kubernetes namespace.",category:ue,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter pods."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter pods.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the pod list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"If true, list pods across all namespaces.",default:!1}},required:[]},execute:async n=>{let e=["get","pods"],t=n.output;t?e.push("-o",t):e.push("-o","wide"),n.allNamespaces&&e.push("--all-namespaces"),n.namespace&&!n.allNamespaces&&e.push("-n",N(n.namespace,"namespace"));let o=sy(n.labelSelector)??n.labels;return o&&e.push("-l",N(o,"labels")),oe(e)}},Xs={name:"k8s.describe",displayName:"Kubernetes Describe Resource",description:"Describe a Kubernetes resource or resource instance.",category:ue,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to describe, such as pod, service, deployment."},name:{type:"string",description:"Resource name. Optional for cluster-wide descriptions."},namespace:{type:"string",description:"Namespace containing the resource."}},required:["resource"]},execute:async n=>{let t=["describe",N(n.resource,"resource")];return n.name&&t.push(N(n.name,"name")),n.namespace&&t.push("-n",N(n.namespace,"namespace")),oe(t)}},Ys={name:"k8s.get_logs",displayName:"Kubernetes Get Pod Logs",description:"Fetch logs from a Kubernetes pod, optionally from a specific container.",category:ue,parameters:{type:"object",properties:{podName:{type:"string",description:"The name of the pod to fetch logs from."},namespace:{type:"string",description:"Namespace of the pod."},container:{type:"string",description:"Container name inside the pod."},tailLines:{type:"number",description:"Number of log lines to show from the end.",default:100},since:{type:"string",description:"Return logs newer than a relative duration like 5m or 1h."}},required:["podName"]},execute:async n=>{let e=["logs",N(n.podName,"podName")];return n.container&&e.push("-c",N(n.container,"container")),n.namespace&&e.push("-n",N(n.namespace,"namespace")),typeof n.tailLines=="number"&&e.push("--tail",`${n.tailLines}`),n.since&&e.push("--since",N(n.since,"since")),oe(e)}},Zs={name:"k8s.apply_manifest",displayName:"Kubernetes Apply Manifest",description:"Apply a Kubernetes manifest from a file path or inline YAML content.",category:ue,parameters:{type:"object",properties:{path:{type:"string",description:"Path to the manifest file to apply."},manifest:{type:"string",description:"Inline YAML manifest to apply if no path is provided."},namespace:{type:"string",description:"Namespace to apply the manifest into, if supported by the manifest."},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without applying changes.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will change cluster state by applying a Kubernetes manifest.",showArgs:["path","namespace"]},execute:async n=>{let e=n.path,t=n.manifest,o=["apply"];if(n.dryRun&&o.push("--dry-run=client"),o.push("-f"),e)return o.push(N(e,"path")),n.namespace&&o.push("-n",N(n.namespace,"namespace")),oe(o);if(!t)throw new Error("Either path or manifest is required to apply a Kubernetes manifest.");return n.namespace&&o.push("-n",N(n.namespace,"namespace")),o.push("-"),oe(o,t)}},ei={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:ue,parameters:{type:"object",properties:{resource:{type:"string",description:"Resource type to delete, such as pod, service, deployment."},name:{type:"string",description:"Name of the resource to delete."},namespace:{type:"string",description:"Namespace containing the resource."},path:{type:"string",description:"Path to a manifest file that contains the resources to delete."},force:{type:"boolean",description:"Force deletion of the resource.",default:!1},dryRun:{type:"boolean",description:"If true, perform a client-side dry run without deleting resources.",default:!1}},required:[]},confirmation:{level:"high",reason:"This will delete resources from the Kubernetes cluster.",showArgs:["resource","name","path"]},execute:async n=>{let e=n.path,t=n.resource,o=n.name;if(e){let s=["delete"];return n.dryRun&&s.push("--dry-run=client"),s.push("-f",N(e,"path")),n.namespace&&s.push("-n",N(n.namespace,"namespace")),oe(s)}if(!t||!o)throw new Error("resource and name are required unless a manifest path is provided.");let r=["delete",N(t,"resource"),N(o,"name")];return n.namespace&&r.push("-n",N(n.namespace,"namespace")),n.force&&r.push("--force","--grace-period=0"),n.dryRun&&r.push("--dry-run=client"),oe(r)}},ti={name:"k8s.list_services",displayName:"Kubernetes List Services",description:"List services in the current or a specific Kubernetes namespace.",category:ue,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},output:{type:"string",description:"Output format for the service list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List services across all namespaces.",default:!1}},required:[]},execute:async n=>{let e=["get","services"],t=n.output;return e.push("-o",t||"wide"),n.allNamespaces&&e.push("--all-namespaces"),n.namespace&&!n.allNamespaces&&e.push("-n",N(n.namespace,"namespace")),oe(e)}},oi={name:"k8s.list_deployments",displayName:"Kubernetes List Deployments",description:"List deployments in the current or a specific Kubernetes namespace.",category:ue,parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to query. If omitted, uses the current namespace."},labels:{type:"string",description:"Label selector to filter deployments."},labelSelector:{type:"object",description:"Map of label key/value pairs to filter deployments.",additionalProperties:{type:"string"}},output:{type:"string",description:"Output format for the deployment list.",enum:["wide","name","json","yaml"],default:"wide"},allNamespaces:{type:"boolean",description:"List deployments across all namespaces.",default:!1}},required:[]},execute:async n=>{let e=["get","deployments"],t=n.output;e.push("-o",t||"wide"),n.allNamespaces&&e.push("--all-namespaces"),n.namespace&&!n.allNamespaces&&e.push("-n",N(n.namespace,"namespace"));let o=sy(n.labelSelector)??n.labels;return o&&e.push("-l",N(o,"labels")),oe(e)}},ri={name:"k8s.get_config_map",displayName:"Kubernetes Get ConfigMap",description:"Retrieve a ConfigMap from a Kubernetes namespace.",category:ue,parameters:{type:"object",properties:{name:{type:"string",description:"ConfigMap name."},namespace:{type:"string",description:"Namespace containing the ConfigMap."},output:{type:"string",description:"Output format, such as yaml or json.",enum:["yaml","json"],default:"yaml"}},required:["name"]},execute:async n=>{let e=["get","configmap",N(n.name,"name"),"-o",n.output||"yaml"];return n.namespace&&e.push("-n",N(n.namespace,"namespace")),oe(e)}},ni={name:"k8s.switch_context",displayName:"Kubernetes Switch Context",description:"Switch the active kubectl context to a different Kubernetes cluster or namespace configuration.",category:ue,parameters:{type:"object",properties:{context:{type:"string",description:"The kubeconfig context to switch to."}},required:["context"]},execute:async n=>oe(["config","use-context",N(n.context,"context")])},si={name:"k8s.get_namespaces",displayName:"Kubernetes Get Namespaces",description:"List namespaces in the current Kubernetes context.",category:ue,parameters:{type:"object",properties:{output:{type:"string",description:"Output format for the namespace list.",enum:["wide","name","json","yaml"],default:"wide"}},required:[]},execute:async n=>oe(["get","namespaces","-o",n.output||"wide"])},ii={name:"k8s.wait_for_deployment",displayName:"Kubernetes Wait For Deployment",description:"Wait for a Kubernetes deployment to complete its rollout.",category:ue,parameters:{type:"object",properties:{name:{type:"string",description:"Deployment name to wait for."},namespace:{type:"string",description:"Namespace containing the deployment."},timeout:{type:"string",description:"Timeout duration, e.g. 300s or 5m.",default:"300s"}},required:["name"]},execute:async n=>{let e=n.timeout,t=["rollout","status",`deployment/${N(n.name,"name")}`,"--timeout",e||"300s"];return n.namespace&&t.push("-n",N(n.namespace,"namespace")),oe(t,void 0,KT(e))}};var JT={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:[Vs,Xs,Ys,Zs,ei,ti,oi,ri,ni,si,ii]};c();c();P();import{spawn as QT}from"child_process";import{EventEmitter as VT}from"events";var Kr=class extends Error{constructor(e,t){super(`MCP request timed out after ${t}ms: ${e}`),this.name="McpTimeoutError"}},ve=class extends Error{constructor(t,o){super(t);this.exitCode=o;this.name="McpConnectionError"}exitCode},Ro=class extends VT{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 ve("Client is shutting down");if(this.buffer="",this.process=QT(this.config.command,this.config.args||[],{env:{...process.env,...this.config.env},stdio:["pipe","pipe","pipe"]}),!this.process.stdout||!this.process.stdin)throw new ve("Failed to spawn MCP server: stdout/stdin unavailable");this.process.stdout.on("data",t=>{this.handleData(t)}),this.process.stderr&&this.process.stderr.on("data",t=>{M(`[MCP server stderr] ${t.toString().trim()}`)}),this.process.on("error",t=>{this._connected=!1,this.emit("error",t)}),this.process.on("exit",t=>{let o=this._connected;this._connected=!1,this.process=null,this.rejectAllPending(new ve(`MCP server exited with code ${t}`,t)),this.emit("close",t),o&&!this._shuttingDown&&this.autoReconnect&&this.attemptReconnect()}),this._reconnectAttempts=0,await this.initializeServer(),this._connected=!0}async attemptReconnect(){if(this._reconnectAttempts>=this.maxReconnectAttempts){this.emit("reconnect_failed",this._reconnectAttempts);return}this._reconnectAttempts++;let t=this._reconnectAttempts;if(this.emit("reconnecting",{attempt:t,max:this.maxReconnectAttempts}),await new Promise(o=>setTimeout(o,this.reconnectDelayMs*t)),!this._shuttingDown)try{await this.connect(),this.emit("reconnected",{attempt:t})}catch(o){this.emit("reconnect_error",{attempt:t,error:o})}}handleData(t){this.buffer+=t.toString();let o;for(;(o=this.buffer.indexOf(`
|
|
360
|
+
`))!==-1;){let r=this.buffer.slice(0,o).trim();if(this.buffer=this.buffer.slice(o+1),r)try{let s=JSON.parse(r);this.handleMessage(s)}catch{}}}handleMessage(t){if(t.id&&(t.result!==void 0||t.error)){let o=this.messageQueue.get(t.id);o&&(o.timer&&clearTimeout(o.timer),t.error?o.reject(new Error(t.error.message)):o.resolve(t.result),this.messageQueue.delete(t.id))}else t.method&&(this.emit("notification",t),this.emit(t.method,t.params))}async callTool(t,o={},r){return this.request("tools/call",{name:t,arguments:o},r)}async readResource(t,o){return this.request("resources/read",{uri:t},o)}async request(t,o,r){if(!this.process||!this.process.stdin)throw new ve("Client not connected");let s=this.nextId++,i=r??this.defaultTimeoutMs,a={jsonrpc:"2.0",id:s,method:t,params:o};return new Promise((l,p)=>{let m;i>0&&(m=setTimeout(()=>{let d=this.messageQueue.get(s);d&&(this.messageQueue.delete(s),d.reject(new Kr(t,i)))},i)),this.messageQueue.set(s,{resolve:l,reject:p,timer:m});try{this.process.stdin.write(JSON.stringify(a)+`
|
|
361
|
+
`)}catch(d){m&&clearTimeout(m),this.messageQueue.delete(s),p(d)}})}async disconnect(t=3e3){if(this._shuttingDown=!0,this.rejectAllPending(new ve("Client disconnecting")),!this.process){this._shuttingDown=!1;return}let o=this.process;return new Promise(r=>{let s=!1,i=()=>{s||(s=!0,this.process=null,this._connected=!1,this._shuttingDown=!1,r())};o.once("exit",i),o.kill("SIGTERM"),setTimeout(()=>{if(!s){try{o.kill("SIGKILL")}catch{}i()}},t)})}kill(){this._shuttingDown=!0,this.rejectAllPending(new ve("Client killed")),this.process&&(this.process.kill("SIGKILL"),this.process=null),this._connected=!1,this._shuttingDown=!1}rejectAllPending(t){for(let[o,r]of this.messageQueue)r.timer&&clearTimeout(r.timer),r.reject(t);this.messageQueue.clear()}};P();var Jr=class{constructor(e){this.config=e}config;clients=new Map;serverConfigs=new Map;toolDefinitions=new Map;toolOwners=new Map;async connectServer(e){let{name:t,displayName:o,toolPrefix:r,...s}=e;C(`[MCP] Connecting to server: ${o||t}`);try{let i=new Ro({...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 ee(`[MCP] Failed to connect to ${t}: ${i}`),i}}async connectAll(){let e=this.config.servers.filter(t=>t.autoConnect!==!1).map(t=>this.connectServer(t));await Promise.allSettled(e)}async disconnectServer(e){let t=this.clients.get(e);if(!t){M(`[MCP] Server ${e} not found`);return}C(`[MCP] Disconnecting from ${e}`);for(let[o,r]of this.toolOwners)r===e&&(this.toolDefinitions.delete(o),this.toolOwners.delete(o));await t.disconnect(),this.clients.delete(e),this.serverConfigs.delete(e)}async disconnectAll(){let e=Array.from(this.clients.keys()).map(t=>this.disconnectServer(t));await Promise.allSettled(e)}getToolDefinitions(){return Array.from(this.toolDefinitions.values())}getConnectedServers(){return Array.from(this.clients.keys())}isServerConnected(e){return this.clients.get(e)?.connected??!1}convertMcpTool(e,t,o,r){let s={type:"object",properties:e.inputSchema.properties||{},required:e.inputSchema.required||[]};return{name:`${o}${e.name}`,displayName:e.name,description:e.description||`MCP tool from ${t}`,category:"mcp",parameters:s,execute:async i=>{try{C(`[MCP] Executing ${e.name} on ${t}`);let a=await r.callTool(e.name,i);return JSON.stringify(a)}catch(a){throw ee(`[MCP] Tool execution failed: ${a}`),a}}}}setupClientEvents(e,t){e.on("error",o=>{ee(`[MCP] ${t} error: ${o}`)}),e.on("close",o=>{M(`[MCP] ${t} closed with code ${o}`)}),e.on("reconnecting",({attempt:o,max:r})=>{C(`[MCP] ${t} reconnecting (${o}/${r})`)}),e.on("reconnected",({attempt:o})=>{C(`[MCP] ${t} reconnected after ${o} attempts`),this.refreshServerTools(t).catch(r=>{ee(`[MCP] ${t} tool refresh failed after reconnect: ${r}`)})}),e.on("reconnect_failed",o=>{ee(`[MCP] ${t} failed to reconnect after ${o} attempts`)}),e.on("notification",o=>{C(`[MCP] ${t} notification: ${JSON.stringify(o)}`)})}removeServerToolDefinitions(e){for(let[t,o]of this.toolOwners)o===e&&(this.toolDefinitions.delete(t),this.toolOwners.delete(t))}async discoverServerTools(e,t,o){let s=(await t.request("tools/list"))?.tools||[];C(`[MCP] Discovered ${s.length} tools from ${e}`),this.removeServerToolDefinitions(e);let i=o.toolPrefix||`mcp.${e}.`;for(let a of s){let l=this.convertMcpTool(a,e,i,t);this.toolDefinitions.set(l.name,l),this.toolOwners.set(l.name,e)}}async refreshServerTools(e){let t=this.clients.get(e),o=this.serverConfigs.get(e);!t||!o||await this.discoverServerTools(e,t,o)}};async function ai(n){let e=new Jr(n);await e.connectAll();let t=e.getToolDefinitions();return{manifest:{key:"mcp-tools",name:"mcp-tools",displayName:"MCP Tools",version:"1.0.0",description:`Tools from ${e.getConnectedServers().length} MCP server(s)`,category:"mcp",author:"Toolpack SDK",tools:t.map(r=>r.name)},tools:t,mcpManager:e}}async function li(n){"mcpManager"in n&&await n.mcpManager.disconnectAll()}c();c();c();c();var ci=`
|
|
203
362
|
You are a planning assistant. Given a user request, create a detailed step-by-step plan.
|
|
204
363
|
|
|
205
364
|
Rules:
|
|
@@ -225,7 +384,7 @@ Rules:
|
|
|
225
384
|
}
|
|
226
385
|
]
|
|
227
386
|
}
|
|
228
|
-
`,
|
|
387
|
+
`,pi=`
|
|
229
388
|
You are executing step {stepNumber} of a plan.
|
|
230
389
|
|
|
231
390
|
Plan summary: {planSummary}
|
|
@@ -244,7 +403,7 @@ IMPORTANT: Your response should be written as if you are directly answering the
|
|
|
244
403
|
Do NOT mention steps, plans, workflow details, or internal process in your response.
|
|
245
404
|
Do NOT say things like "Step 1 is complete" or "proceeding to the next step".
|
|
246
405
|
Just provide the actual answer or result naturally.
|
|
247
|
-
`,
|
|
406
|
+
`,Sj={name:"Direct",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}},iy={name:"Agent",planning:{enabled:!0,planningPrompt:ci},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:pi},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},XT=`
|
|
248
407
|
Create a step-by-step plan for this coding task.
|
|
249
408
|
|
|
250
409
|
Rules:
|
|
@@ -267,7 +426,7 @@ JSON Schema:
|
|
|
267
426
|
}
|
|
268
427
|
]
|
|
269
428
|
}
|
|
270
|
-
`,
|
|
429
|
+
`,YT=`
|
|
271
430
|
Execute step {stepNumber}: {stepDescription}
|
|
272
431
|
|
|
273
432
|
Plan: {planSummary}
|
|
@@ -276,12 +435,12 @@ Previous: {previousStepsResults}
|
|
|
276
435
|
|
|
277
436
|
Use tools. Be concise. Show code changes clearly.
|
|
278
437
|
No meta-commentary about steps or workflow.
|
|
279
|
-
`,
|
|
280
|
-
Result: ${
|
|
281
|
-
Failed: ${
|
|
282
|
-
Skipped.`)}return
|
|
438
|
+
`,ay={name:"Coding",planning:{enabled:!0,planningPrompt:XT},steps:{enabled:!0,retryOnFailure:!0,allowDynamicSteps:!1,stepPrompt:YT},progress:{enabled:!0},complexityRouting:{enabled:!0,strategy:"single-step",confidenceThreshold:.6}},ly={name:"Chat",planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!1}};var cy={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:iy,toolSearch:{alwaysLoadedTools:["fs.read_file","fs.write_file","fs.list_dir","web.search","web.fetch","skill.search","skill.read"]}},py={name:"chat",displayName:"Chat",description:"Conversational assistant with web access",systemPrompt:["You are a conversational AI assistant with web access.","You can search the web, fetch online content, and make HTTP requests.","You do NOT have access to the local filesystem, command execution, or code modification.","Answer questions using your knowledge and web tools when helpful.","If the user asks for local file operations or code changes,","explain that you are in Chat mode and suggest they switch to Agent mode."].join(" "),allowedToolCategories:["network"],blockedToolCategories:["filesystem","execution","system","coding","git","database"],allowedTools:[],blockedTools:[],blockAllTools:!1,baseContext:{includeWorkingDirectory:!1,includeToolCategories:!0},workflow:ly,toolSearch:{alwaysLoadedTools:["web.search","web.fetch","fs.read_file","fs.list_dir"]}},my={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:ay,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"]}},Qr=[cy,my,py],dt="chat";var $o=class{modes=new Map;orderedNames=[];constructor(){for(let e of Qr)this.register(e)}register(e){if(!e.name||typeof e.name!="string")throw new Error("ModeConfig.name is required and must be a non-empty string");if(!e.displayName||typeof e.displayName!="string")throw new Error("ModeConfig.displayName is required and must be a non-empty string");if(typeof e.systemPrompt!="string")throw new Error("ModeConfig.systemPrompt must be a string (can be empty for passthrough)");if(e.blockAllTools!==void 0&&typeof e.blockAllTools!="boolean")throw new Error("ModeConfig.blockAllTools must be a boolean");let t=["allowedToolCategories","blockedToolCategories","allowedTools","blockedTools"];for(let r of t)if(e[r]!==void 0&&!Array.isArray(e[r]))throw new Error(`ModeConfig.${r} must be an array`);let o=this.modes.has(e.name);this.modes.set(e.name,e),o||this.orderedNames.push(e.name)}get(e){return this.modes.get(e)}has(e){return this.modes.has(e)}getAll(){let e=[];for(let t of this.orderedNames){let o=this.modes.get(t);o&&e.push(o)}return e}getNames(){return[...this.orderedNames]}getDefault(){let e=this.modes.get(dt);if(!e)throw new Error(`Default mode "${dt}" not found in registry`);return e}getNext(e){let t=this.orderedNames.indexOf(e),o=t===-1?0:(t+1)%this.orderedNames.length,r=this.orderedNames[o],s=this.modes.get(r);if(!s)throw new Error(`Mode "${r}" not found in registry`);return s}get size(){return this.modes.size}remove(e){if(Qr.some(r=>r.name===e))return!1;let o=this.modes.delete(e);return o&&(this.orderedNames=this.orderedNames.filter(r=>r!==e)),o}};c();function ZT(n){return{name:n.name,displayName:n.displayName,description:n.description||n.displayName,systemPrompt:n.systemPrompt,allowedToolCategories:n.allowedToolCategories||[],blockedToolCategories:n.blockedToolCategories||[],allowedTools:n.allowedTools||[],blockedTools:n.blockedTools||[],blockAllTools:n.blockAllTools||!1,baseContext:n.baseContext,workflow:n.workflow}}c();var mi={planning:{enabled:!1},steps:{enabled:!1},progress:{enabled:!0}};c();P();var ex=ci,_o=class{client;config;constructor(e,t){this.client=e,this.config=t}async createPlan(e,t){let o=this.config?.planningPrompt||ex,r=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="${r}..."`);let s=e.messages.filter(p=>p.role==="system"),i=e.messages.filter(p=>p.role!=="system"),a=[{role:"system",content:o},...s,...i],l={...e,tools:void 0,tool_choice:"none",response_format:"json_object",messages:a};try{let p=await this.client.generate(l,t),m=this.parsePlan(p.content||"",e,p);return C(`[Planner] createPlan() succeeded plan.id=${m.id} steps=${m.steps.length}`),m}catch(p){return M(`[Planner] createPlan() failed, using fallback: ${p.message}`),this.createFallbackPlan(e)}}parsePlan(e,t,o){try{let r=JSON.parse(e);if(!r.summary||!Array.isArray(r.steps))throw new Error("Invalid plan structure: missing summary or steps array");let s=this.config?.maxSteps??20,i=r.steps.slice(0,s);r.steps.length>s&&M(`[Planner] parsePlan() truncated ${r.steps.length} steps to maxSteps=${s}`),y(`[Planner] parsePlan() parsed ${i.length} steps successfully`);let a=i.map((p,m)=>({id:`step-${Date.now()}-${m}`,number:p.number||m+1,description:p.description||"Unknown step",expectedTools:p.expectedTools||[],dependsOn:p.dependsOn||[],status:"pending"})),l=t.messages.filter(p=>p.role==="user").map(p=>typeof p.content=="string"?p.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}`,request:l,summary:r.summary,steps:a,status:"draft",createdAt:new Date,planningResponse:o}}catch(r){return M(`[Planner] parsePlan() failed: ${r.message} \u2014 using fallback`),this.createFallbackPlan(t)}}createFallbackPlan(e){M("[Planner] createFallbackPlan() \u2014 creating single-step fallback due to plan generation failure");let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Complex Object]").join("\\n");return{id:`plan-${Date.now()}-fallback`,request:t,summary:"Fallback single-step plan due to generation failure",steps:[{id:"step-1",number:1,description:"Execute the user request",status:"pending",expectedTools:[],dependsOn:[]}],status:"draft",createdAt:new Date}}};c();c();var ut=class{static getProgress(e){let t=e.steps.length,o=e.steps.findIndex(l=>l.status!=="completed"&&l.status!=="skipped");o===-1&&(o=t);let r=t>0?Math.round(o/t*100):0,s=e.steps[o],i=s?s.description:"Done",a="executing";return e.status==="draft"&&(a="planning"),e.status==="approved"&&(a="executing"),e.status==="completed"&&(a="completed"),(e.status==="failed"||e.status==="cancelled")&&(a="failed"),{planId:e.id,currentStep:Math.min(o+1,t),totalSteps:t,percentage:r,currentStepDescription:i,status:a}}static summarizeCompletedSteps(e,t){let o=[];for(let r of e.steps){if(r.id===t)break;if(r.status==="completed"&&r.result){let s=r.result.toolsUsed?.length?` (Tools: ${r.result.toolsUsed.join(", ")})`:"",i=r.result.output||"No output";i.length>500&&(i=i.substring(0,500)+"... [truncated]"),o.push(`Step ${r.number}: ${r.description}${s}
|
|
439
|
+
Result: ${i}`)}else r.status==="failed"?o.push(`Step ${r.number}: ${r.description}
|
|
440
|
+
Failed: ${r.result?.error||"Unknown error"}`):r.status==="skipped"&&o.push(`Step ${r.number}: ${r.description}
|
|
441
|
+
Skipped.`)}return o.length===0?"No previous steps.":o.join(`
|
|
283
442
|
|
|
284
|
-
`)}};
|
|
443
|
+
`)}};P();var tx=pi,ox=`
|
|
285
444
|
Based on the result of the previous step, do we need to add any new steps to our plan before continuing?
|
|
286
445
|
Only add steps if they are absolutely necessary to complete the user's request.
|
|
287
446
|
|
|
@@ -299,46 +458,72 @@ JSON Schema:
|
|
|
299
458
|
{ "description": "What to do", "expectedTools": [] }
|
|
300
459
|
]
|
|
301
460
|
}
|
|
302
|
-
`,
|
|
303
|
-
... [truncated]`),m.push({role:"assistant",content:
|
|
304
|
-
`)||"None",
|
|
461
|
+
`,Eo=class{client;config;constructor(e,t){this.client=e,this.config=t}async executeStep(e,t,o,r){let s=Date.now();y(`[StepExecutor] executeStep() step=${e.number} "${e.description}" expectedTools=${e.expectedTools?.join(",")||"none"}`);let i=this.buildStepRequest(e,t,o);try{let a=await this.client.generate(i,r),l=new Set;a.tool_calls&&a.tool_calls.forEach(m=>l.add(m.name));let p=Date.now()-s;return C(`[StepExecutor] Step ${e.number} completed in ${p}ms toolsUsed=[${Array.from(l).join(", ")||"none"}] output_len=${a.content?.length??0}`),{success:!0,output:a.content||"Step completed successfully.",toolsUsed:Array.from(l),duration:p,response:a}}catch(a){let l=Date.now()-s;return M(`[StepExecutor] Step ${e.number} failed in ${l}ms: ${a.message}`),{success:!1,error:a.message||"Unknown execution error",duration:l}}}async*streamStep(e,t,o,r){y(`[StepExecutor] streamStep() step=${e.number} "${e.description}"`);let s=this.buildStepRequest(e,t,o);yield*this.client.stream(s,r)}buildStepRequest(e,t,o){let r=ut.summarizeCompletedSteps(t,e.id),i=(this.config?.stepPrompt||tx).replace("{stepNumber}",e.number.toString()).replace("{planSummary}",t.summary).replace("{stepDescription}",e.description).replace("{previousStepsResults}",r),a=o.messages.filter(d=>d.role==="system"),l=o.messages.filter(d=>d.role!=="system"),p=[...a,...l],m=[];for(let d of t.steps){if(d.id===e.id)break;if(d.status==="completed"&&d.result?.output){let g=d.result.output;g.length>2e3&&(g=g.substring(0,2e3)+`
|
|
462
|
+
... [truncated]`),m.push({role:"assistant",content:g}),m.push({role:"user",content:`Step ${d.number} is complete. Now proceed with the next step.`})}}return{...o,messages:[{role:"system",content:i},...p,...m],tool_choice:"auto"}}async checkForDynamicSteps(e,t,o,r){if(!this.config?.allowDynamicSteps)return[];let s=t.steps.length,i=this.config.maxTotalSteps??50;if(s>=i)return y(`[StepExecutor] checkForDynamicSteps() skipped \u2014 already at maxTotalSteps=${i}`),[];y(`[StepExecutor] checkForDynamicSteps() after step=${e.number} currentTotal=${s} max=${i}`);let a=t.steps.filter(w=>w.status==="pending"&&w.number>e.number).map(w=>`${w.number}. ${w.description}`).join(`
|
|
463
|
+
`)||"None",l=ox.replace("{{REMAINING_STEPS}}",a),p=o.messages.filter(w=>w.role==="system"),m=o.messages.filter(w=>w.role!=="system"),d=[...p,...m],g={...o,tool_choice:"none",response_format:"json_object",messages:[...d,{role:"assistant",content:e.result?.output||""},{role:"user",content:l}]};try{let w=await this.client.generate(g,r),b=JSON.parse(w.content||'{"steps": []}');if(Array.isArray(b.steps)&&b.steps.length>0){let T=i-s,x=b.steps.slice(0,T),S=new Set(t.steps.map(D=>this.normalizeStepDescription(D.description))),v=x.filter(D=>{let F=this.normalizeStepDescription(D.description||"");return S.has(F)?!1:(S.add(F),!0)});return v.length===0?(y("[StepExecutor] checkForDynamicSteps() all proposed steps were duplicates \u2014 skipping"),[]):(C(`[StepExecutor] checkForDynamicSteps() adding ${v.length} dynamic step(s) after step ${e.number}`),v.map((D,F)=>({id:`step-${Date.now()}-dyn-${F}`,number:0,description:D.description||"Dynamic step",expectedTools:D.expectedTools||[],dependsOn:[e.id],status:"pending"})))}}catch{}return[]}normalizeStepDescription(e){return e.toLowerCase().replace(/[^a-z0-9\s]/g,"").replace(/\s+/g," ").trim().split(" ").filter(t=>t.length>2).sort().join(" ")}};c();import{EventEmitter as rx}from"events";P();var Vr=class extends rx{client;config;planner;stepExecutor;queryClassifier;pendingApprovals=new Map;constructor(e,t,o){super(),this.client=e,this.config=t,this.queryClassifier=o||new Ze,this.planner=new _o(e,t.planning),this.stepExecutor=new Eo(e,t.steps)}getConfig(){return this.config}setConfig(e){this.config=e,this.planner=new _o(this.client,e.planning),this.stepExecutor=new Eo(this.client,e.steps)}shouldRouteSimpleQuery(e){if(!this.config.complexityRouting?.enabled)return!1;let t=this.config.complexityRouting.strategy??"single-step";if(t==="disabled")return!1;let o=We(e.messages);if(!o)return!1;let r=this.queryClassifier.classify(o),s=this.config.complexityRouting.confidenceThreshold??.6,i=!1;switch(r.type){case"action":i=!1;break;case"conversational":i=!0;break;case"analytical":i=r.confidence>=s;break}return y(`[Workflow] shouldRouteSimpleQuery() type=${r.type} confidence=${r.confidence.toFixed(2)} threshold=${s} shouldRoute=${i} strategy=${t}`),i}async execute(e,t){if(this.shouldRouteSimpleQuery(e))return this.executeDirect(e,t);let o=this.config.planning?.enabled,r=this.config.steps?.enabled;if(y(`[Workflow] execute() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r)return y("[Workflow] execute() mode=direct"),this.executeDirect(e,t);let s=null;if(o){if(y("[Workflow] execute() mode=planning \u2014 creating plan"),s=await this.createPlan(e,t),this.emit("workflow:plan_created",s),this.config.planning?.requireApproval){C(`[Workflow] Plan "${s.id}" requires approval \u2014 waiting`),this.emitProgress(s,"awaiting_approval","Waiting for plan approval");let i=await this.waitForApproval(s.id);if(this.emit("workflow:plan_decision",s,i),!i)return C(`[Workflow] Plan "${s.id}" rejected by user`),s.status="cancelled",this.emitProgress(s,"failed","Plan rejected by user"),{success:!1,plan:s,error:"Plan rejected by user",metrics:{totalDuration:0,stepsCompleted:0,stepsFailed:0,retriesUsed:0}};C(`[Workflow] Plan "${s.id}" approved`)}s.status="approved"}return r?(s||(y("[Workflow] execute() mode=steps-only \u2014 creating implicit plan"),s=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",s),s.status="approved"),this.executeStepByStep(s,e,t)):s?(y("[Workflow] execute() mode=plan-direct (planning only, no steps)"),this.executePlanDirect(s,e,t)):this.executeDirect(e,t)}async executeDirect(e,t){let o=Date.now(),r=this.createDummyPlan(e);y(`[Workflow] executeDirect() provider=${t??"default"}`);try{this.emitProgress(r,"executing","Direct execution");let s=await this.client.generate(e,t);r.status="completed",r.completedAt=new Date,r.steps[0].status="completed";let i=Date.now()-o;y(`[Workflow] executeDirect() completed in ${i}ms content_len=${s.content?.length??0}`);let a={success:!0,plan:r,output:s.content||void 0,metrics:{totalDuration:Date.now()-o,stepsCompleted:1,stepsFailed:0,retriesUsed:0}};return this.emit("workflow:completed",r,a),this.emitProgress(r,"completed","Done"),a}catch(s){r.status="failed",r.completedAt=new Date,r.steps[0].status="failed",M(`[Workflow] executeDirect() failed: ${s.message}`);let i={success:!1,plan:r,error:s.message,metrics:{totalDuration:Date.now()-o,stepsCompleted:0,stepsFailed:1,retriesUsed:0}};return this.emit("workflow:failed",r,s),this.emitProgress(r,"failed","Execution failed"),i}}async createPlan(e,t){y(`[Workflow] createPlan() provider=${t??"default"}`);let o=this.createDummyPlan(e);o.status="draft",this.emitProgress(o,"planning","Creating plan...");let r=await this.planner.createPlan(e,t);return C(`[Workflow] createPlan() completed plan.id=${r.id} steps=${r.steps.length}`),r}async executeStepByStep(e,t,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),C(`[Workflow] executeStepByStep() plan.id=${e.id} steps=${e.steps.length} maxRetries=${this.config.steps?.maxRetries??3}`);let r=Date.now(),s=0;for(let l=0;l<e.steps.length;l++){let p=e.steps[l];if(p.status!=="pending"&&p.status!=="failed")continue;if(p.dependsOn?.length){let b=p.dependsOn.filter(T=>{let x=e.steps.find(S=>S.id===String(T)||S.number===Number(T));return x?x.status!=="completed":!1});if(b.length>0){y(`[Workflow] Step ${p.number} skipped \u2014 unmet deps: ${b.join(", ")}`),p.status="skipped",p.result={success:!1,error:`Unmet dependencies: ${b.join(", ")}`};continue}}p.status="in_progress",this.emit("workflow:step_start",p,e),this.emitProgress(e,"executing",p.description),C(`[Workflow] Step ${p.number}/${e.steps.length} starting: "${p.description}"`);let m=0,d=this.config.steps?.maxRetries??3,g=null,w=!1;for(;m<=d;)try{let b=await this.stepExecutor.executeStep(p,e,t,o);if(b.success){p.status="completed",p.result=b,this.emit("workflow:step_complete",p,e),y(`[Workflow] Step ${p.number} completed in ${b.duration??0}ms toolsUsed=${(b.toolsUsed??[]).join(",")||"none"}`),w=!0;break}else throw new Error(b.error||"Step returned unsuccessful result")}catch(b){if(g=b,m++,m<=d&&this.config.steps?.retryOnFailure)s++,M(`[Workflow] Step ${p.number} failed (attempt ${m}/${d}), retrying: ${g.message}`),this.emit("workflow:step_retry",p,m,e),this.emitProgress(e,"executing",`[Retry ${m}] ${p.description}`);else{M(`[Workflow] Step ${p.number} failed permanently: ${g.message}`),p.status="failed",p.result={success:!1,error:g.message},this.emit("workflow:step_failed",p,g,e);break}}if(!w){let b=this.config.onFailure?.strategy||"abort";if(y(`[Workflow] Step ${p.number} failed \u2014 applying strategy="${b}"`),b==="abort"){e.status="failed",e.completedAt=new Date;let T={success:!1,plan:e,error:`Step ${p.number} failed: ${g?.message}`,metrics:this.computeMetrics(e,r,s)};return this.emit("workflow:failed",e,g),this.emitProgress(e,"failed","Workflow aborted due to step failure"),T}else if(b==="ask_user"){if(this.emitProgress(e,"awaiting_approval",`Step failed: ${g?.message}. Continue?`),!await this.waitForApproval(e.id)){e.status="failed",e.completedAt=new Date;let x={success:!1,plan:e,error:`Workflow aborted by user after step ${p.number} failure`,metrics:this.computeMetrics(e,r,s)};return this.emit("workflow:failed",e,new Error(x.error)),x}p.status="skipped"}else p.status="skipped"}if(w&&this.config.steps?.allowDynamicSteps){let b=await this.stepExecutor.checkForDynamicSteps(p,e,t,o);if(b.length>0){let T=p.number+1;for(let x of b)x.number=T++;for(let x=l+1;x<e.steps.length;x++)e.steps[x].number=T++;e.steps.splice(l+1,0,...b),b.forEach(x=>this.emit("workflow:step_added",x,e))}}}let i=this.computeMetrics(e,r,s);e.status="completed",e.completedAt=new Date,e.metrics=i,C(`[Workflow] executeStepByStep() completed plan.id=${e.id} duration=${i.totalDuration}ms stepsCompleted=${i.stepsCompleted} stepsFailed=${i.stepsFailed} retriesUsed=${s}`);let a={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};return this.emit("workflow:completed",e,a),this.emitProgress(e,"completed","Done"),a}async executePlanDirect(e,t,o){let r=Date.now();e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e),this.emitProgress(e,"executing","Executing plan"),y(`[Workflow] executePlanDirect() plan.id=${e.id} steps=${e.steps.length} provider=${o??"default"}`);let s=`
|
|
305
464
|
You have created the following plan to fulfill the request:
|
|
306
465
|
Summary: ${e.summary}
|
|
307
466
|
|
|
308
467
|
Steps:
|
|
309
|
-
${e.steps.map(
|
|
468
|
+
${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
|
|
310
469
|
`)}
|
|
311
470
|
|
|
312
471
|
Execute this plan now.
|
|
313
|
-
`.trim(),
|
|
472
|
+
`.trim(),i={...t,messages:[{role:"system",content:s},...t.messages]};try{let a=await this.client.generate(i,o);e.steps.forEach(p=>{p.status="completed",p.result={success:!0,output:a.content||""}}),e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,r,0),y(`[Workflow] executePlanDirect() completed plan.id=${e.id} duration=${Date.now()-r}ms`);let l={success:!0,plan:e,output:a.content||void 0,metrics:e.metrics};return this.emit("workflow:completed",e,l),this.emitProgress(e,"completed","Done"),l}catch(a){e.status="failed",e.completedAt=new Date,M(`[Workflow] executePlanDirect() failed plan.id=${e.id}: ${a.message}`);let l={success:!1,plan:e,error:a.message,metrics:this.computeMetrics(e,r,0)};return this.emit("workflow:failed",e,a),this.emitProgress(e,"failed","Execution failed"),l}}emitProgress(e,t,o){if(!this.config.progress?.enabled)return;let r=ut.getProgress(e);t&&(r.status=t),o&&(r.currentStepDescription=o),this.emit("workflow:progress",r)}computeMetrics(e,t,o){return{totalDuration:Date.now()-t,stepsCompleted:e.steps.filter(r=>r.status==="completed").length,stepsFailed:e.steps.filter(r=>r.status==="failed").length,retriesUsed:o}}summarizePlanResult(e){return`Workflow completed.
|
|
314
473
|
Summary: ${e.summary}
|
|
315
474
|
Steps:
|
|
316
475
|
`+e.steps.map(t=>`[${t.status.toUpperCase()}] ${t.description}`).join(`
|
|
317
|
-
`)}extractFinalOutput(e){let t=e.steps[e.steps.length-1];if(t&&/synthesize|summarize|consolidate|combine/i.test(t.description)&&e.steps.length>1)for(let
|
|
476
|
+
`)}extractFinalOutput(e){let t=e.steps[e.steps.length-1];if(t&&/synthesize|summarize|consolidate|combine/i.test(t.description)&&e.steps.length>1)for(let r=e.steps.length-1;r>=0;r--){let s=e.steps[r];if(s.status==="completed"&&s.result?.output)return s.result.output}else{let r=[];for(let s of e.steps)s.status==="completed"&&s.result?.output&&r.push(s.result.output);if(r.length>0)return r.join(`
|
|
318
477
|
|
|
319
|
-
`)}return e.steps.length===0||e.steps.every(
|
|
478
|
+
`)}return e.steps.length===0||e.steps.every(r=>r.status==="pending")?e.summary:this.summarizePlanResult(e)}extractFinalResponse(e){for(let t=e.steps.length-1;t>=0;t--){let o=e.steps[t];if(o.status==="completed"&&o.result?.response)return o.result.response}}createDummyPlan(e){let t=e.messages.filter(o=>o.role==="user").map(o=>typeof o.content=="string"?o.content:"[Object]").join("\\n");return{id:`plan-direct-${Date.now()}`,request:t,summary:"Direct execution",steps:[{id:"step-1",number:1,description:"Execute request",status:"pending",dependsOn:[],expectedTools:[]}],status:"in_progress",createdAt:new Date}}async*stream(e,t){let o=this.config.planning?.enabled,r=this.config.steps?.enabled;if(y(`[Workflow] stream() planningEnabled=${o} stepsEnabled=${r} provider=${t??"default"}`),!o&&!r){y("[Workflow] stream() mode=direct"),yield*this.streamDirect(e,t);return}let s=null;if(o){if(yield{delta:"",workflowStep:{number:0,description:"Creating plan..."}},s=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",s),this.config.planning?.requireApproval){this.emitProgress(s,"awaiting_approval","Waiting for plan approval"),yield{delta:`
|
|
320
479
|
|
|
321
480
|
**Plan Created:**
|
|
322
|
-
${
|
|
481
|
+
${s.summary}
|
|
323
482
|
|
|
324
483
|
Steps:
|
|
325
|
-
${
|
|
484
|
+
${s.steps.map(a=>`${a.number}. ${a.description}`).join(`
|
|
326
485
|
`)}
|
|
327
486
|
|
|
328
|
-
*Waiting for approval...*`,workflowStep:{number:0,description:"Awaiting approval"}};let
|
|
487
|
+
*Waiting for approval...*`,workflowStep:{number:0,description:"Awaiting approval"}};let i=await this.waitForApproval(s.id);if(this.emit("workflow:plan_decision",s,i),!i){s.status="cancelled",yield{delta:`
|
|
329
488
|
|
|
330
|
-
*Plan rejected by user.*`,finish_reason:"stop"};return}}
|
|
489
|
+
*Plan rejected by user.*`,finish_reason:"stop"};return}}s.status="approved"}if(r){s||(s=await this.planner.createPlan(e,t),this.emit("workflow:plan_created",s),s.status="approved"),yield*this.streamStepByStep(s,e,t);return}if(s){yield*this.streamPlanDirect(s,e,t);return}yield*this.streamDirect(e,t)}async*streamDirect(e,t){yield*this.client.stream(e,t)}async*streamStepByStep(e,t,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let r=Date.now(),s=0;for(let a=0;a<e.steps.length;a++){if(t.signal?.aborted){e.status="cancelled",e.completedAt=new Date,this.emit("workflow:failed",e,new Error("Interrupted by user"));return}let l=e.steps[a];if(l.status!=="pending"&&l.status!=="failed")continue;if(l.dependsOn?.length){let b=l.dependsOn.filter(T=>{let x=e.steps.find(S=>S.id===String(T)||S.number===Number(T));return x?x.status!=="completed":!1});if(b.length>0){l.status="skipped",l.result={success:!1,error:`Unmet dependencies: ${b.join(", ")}`};continue}}l.status="in_progress",this.emit("workflow:step_start",l,e),this.emitProgress(e,"executing",l.description);let p=0,m=this.config.steps?.maxRetries??3,d=null,g=!1,w="";for(;p<=m;)try{for await(let b of this.stepExecutor.streamStep(l,e,t,o)){if(t.signal?.aborted){l.status="skipped",e.status="cancelled",e.completedAt=new Date,this.emit("workflow:failed",e,new Error("Interrupted by user"));return}b.delta&&(w+=b.delta),yield{...b,workflowStep:{number:l.number,description:l.description}}}l.status="completed",l.result={success:!0,output:w,duration:Date.now()-r},this.emit("workflow:step_complete",l,e),this.emitProgress(e,"executing"),g=!0;break}catch(b){if(d=b,p++,p<=m&&this.config.steps?.retryOnFailure)s++,this.emit("workflow:step_retry",l,p,e),this.emitProgress(e,"executing",`[Retry ${p}/${m}] ${l.description}`);else{l.status="failed",l.result={success:!1,error:d.message},this.emit("workflow:step_failed",l,d,e);break}}if(!g){let b=this.config.onFailure?.strategy||"abort";if(b==="abort"){e.status="failed",e.completedAt=new Date,this.emit("workflow:failed",e,d),yield{delta:`
|
|
331
490
|
|
|
332
|
-
**Step failed:** ${
|
|
333
|
-
*Workflow aborted.*`,finish_reason:"stop"};return}else
|
|
491
|
+
**Step failed:** ${d?.message}
|
|
492
|
+
*Workflow aborted.*`,finish_reason:"stop"};return}else b==="skip"&&(l.status="skipped",yield{delta:`
|
|
334
493
|
*Step skipped due to failure.*
|
|
335
|
-
`,workflowStep:{number:
|
|
494
|
+
`,workflowStep:{number:l.number,description:l.description}})}if(g&&this.config.steps?.allowDynamicSteps){let b=await this.stepExecutor.checkForDynamicSteps(l,e,t,o);if(b.length>0){let T=l.number+1;for(let x of b)x.number=T++;for(let x=a+1;x<e.steps.length;x++)e.steps[x].number=T++;e.steps.splice(a+1,0,...b),b.forEach(x=>this.emit("workflow:step_added",x,e)),this.emitProgress(e,"executing")}}}e.status="completed",e.completedAt=new Date,e.metrics=this.computeMetrics(e,r,s);let i={success:!0,plan:e,output:this.extractFinalOutput(e),response:this.extractFinalResponse(e),metrics:e.metrics};this.emit("workflow:completed",e,i),this.emitProgress(e,"completed","Done"),yield{delta:"",finish_reason:"stop"}}async*streamPlanDirect(e,t,o){e.status="in_progress",e.startedAt=new Date,this.emit("workflow:started",e);let r=`
|
|
336
495
|
You have created the following plan to fulfill the request:
|
|
337
496
|
Summary: ${e.summary}
|
|
338
497
|
|
|
339
498
|
Steps:
|
|
340
|
-
${e.steps.map(
|
|
499
|
+
${e.steps.map(a=>`${a.number}. ${a.description}`).join(`
|
|
341
500
|
`)}
|
|
342
501
|
|
|
343
502
|
Execute this plan now.
|
|
344
|
-
`.trim(),n={...t,messages:[{role:"system",content:o},...t.messages]},a="";for await(let i of this.client.stream(n,r))i.delta&&(a+=i.delta),yield i;e.steps.forEach(i=>{i.status="completed",i.result={success:!0,output:a}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:a,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)})}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};l();import{EventEmitter as Of}from"events";k();var If=class s extends Of{client;activeProviderName;modeRegistry;workflowExecutor;customProviderNames=new Set;mcpToolProject=null;constructor(e,t,r){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=r;let o=this.client.getProvider(t);o&&this.forwardEvents(o),this.workflowExecutor=new br(this.client,ns,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}static async init(e){let t=Po(e.configPath);ms(t.logging);let r=new Vt,o=Wt(e.configPath);if(r.setConfig(o),e.tools&&await r.loadBuiltIn(),e.customTools&&await r.loadProjects(e.customTools),e.knowledge&&typeof e.knowledge.toTool=="function")try{let T=e.knowledge.toTool(),S={manifest:{key:"knowledge",name:"knowledge",displayName:"Knowledge Base",version:"1.0.0",description:"RAG-powered knowledge base search",tools:["knowledge_search"],category:"search"},tools:[T]};await r.loadProjects([S]),v("[Knowledge] Registered knowledge_search tool")}catch(T){Q(`[Knowledge] Failed to register knowledge tool: ${T}`)}let n=null,a=e.mcp||t.mcp;if(a)try{v("[MCP] Initializing MCP tool integration");let T=await es(a);n=T,await r.loadProjects([T]),v(`[MCP] Loaded ${T.tools.length} tools from MCP servers`)}catch(T){Q(`[MCP] Failed to initialize MCP tools: ${T}`)}let i=t.systemPrompt,c=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},f=new Set,h=e.defaultProvider||e.provider;if(e.providers)for(let[T,S]of Object.entries(e.providers)){let R=T===h,I=await s.createProvider(T,S,e.configPath,!R);I&&(m[T]=I)}else if(e.provider){let T={apiKey:e.apiKey,model:e.model},S=await s.createProvider(e.provider,T,e.configPath,!1);S&&(m[e.provider]=S)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let T=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([S,R])=>(R.name=R.name||S,R));for(let S of T){if(typeof S.generate!="function"||typeof S.stream!="function"||typeof S.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let R=S.name;if(!R)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(m[R])throw new Error(`Custom provider name "${R}" conflicts with a built-in provider designation. Choose a different name.`);f.add(R),m[R]=S}}if(!h&&e.customProviders&&(h=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!h)throw new Error("No default provider specified.");let b=new Zt;if(e.customModes)for(let T of e.customModes)b.register(T);let w={...p,...e.modeOverrides||{}};for(let[T,S]of Object.entries(w)){let R=b.get(T);if(R){S.systemPrompt!==void 0&&(R.systemPrompt=S.systemPrompt),S.toolSearch&&(R.toolSearch={...R.toolSearch||{},...S.toolSearch});for(let[I,U]of Object.entries(S))I!=="systemPrompt"&&I!=="toolSearch"&&(R[I]=U)}}let x=new io({providers:m,defaultProvider:h,toolRegistry:r,toolsConfig:r.getConfig(),systemPrompt:i,disableBaseContext:c}),P=new s(x,h,b);P.customProviderNames=f,P.mcpToolProject=n;let $=e.defaultMode||Ve,C=b.get($);return C&&(x.setMode(C),C.workflow&&P.workflowExecutor.setConfig(C.workflow)),P}static async createProvider(e,t,r,o=!1){if(["openai","anthropic","gemini"].includes(e)){let n=`TOOLPACK_${e.toUpperCase()}_KEY`,a=t.apiKey||process.env[n]||process.env[`${e.toUpperCase()}_API_KEY`];if(!a){if(o)return null;throw new Error(`No API key found for '${e}'. Set ${n} or pass apiKey in config.`)}switch(e){case"openai":return new po(a,t.baseUrl);case"anthropic":return new ao(a,t.baseUrl);case"gemini":return new lo(a)}}if(e==="ollama")return new lt({baseUrl:t.baseUrl||co(r)});if(e.startsWith("ollama-")){let n=t.model||e.replace(/^ollama-/,""),a=t.baseUrl||co(r);return new De({model:n,baseUrl:a})}throw new Error(`Unknown provider type: ${e}`)}async generate(e,t){let r;typeof e=="string"?r={messages:[{role:"user",content:e}],model:""}:r=e;let o=this.getMode();if(o?.workflow?.planning?.enabled||o?.workflow?.steps?.enabled){let n=await this.workflowExecutor.execute(r,t||this.activeProviderName),a=0,i=0,c=0,p={steps:[]};n.plan.planningResponse?.usage&&(a+=n.plan.planningResponse.usage.prompt_tokens,i+=n.plan.planningResponse.usage.completion_tokens||0,c+=n.plan.planningResponse.usage.total_tokens,p.planning=n.plan.planningResponse.usage);for(let f of n.plan.steps)if(f.status==="completed"&&f.result?.response?.usage){let h=f.result.response.usage;a+=h.prompt_tokens,i+=h.completion_tokens||0,c+=h.total_tokens,p.steps.push({stepNumber:f.number,description:f.description,usage:h})}let m={prompt_tokens:a,completion_tokens:i,total_tokens:c};return n.response?{...n.response,content:n.output||n.response.content||null,usage:m,usage_details:p}:{content:n.output||null,usage:m,usage_details:p}}return this.client.generate(r,t)}async*stream(e,t){let r=this.getMode(),o=t||this.activeProviderName;if(r?.workflow?.planning?.enabled||r?.workflow?.steps?.enabled){yield*this.workflowExecutor.stream(e,o);return}yield*this.client.stream(e,t)}async embed(e,t){return this.client.embed(e,t)}setProvider(e){let t=this.client.getProvider(e);this.activeProviderName=e,this.client.setDefaultProvider(e),this.forwardEvents(t)}getProvider(){return this.client.getProvider(this.activeProviderName)}getClient(){return this.client}getWorkflowExecutor(){return this.workflowExecutor}async disconnect(){let e=this.getProvider();e&&"disconnect"in e&&await e.disconnect(),this.mcpToolProject&&await ts(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[r,o]of e.entries()){let n=this.customProviderNames.has(r),a=[];try{a=await o.getModels()}catch(i){E(`[Toolpack] Failed to fetch models for provider '${r}': ${i}`)}t.push({name:r,displayName:o.getDisplayName(),type:n?"custom":"built-in",models:a})}return t}async loadToolProject(e){let t=this.client.getToolRegistry();if(t)await t.loadProject(e);else throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.")}async listModels(){let e=await this.listProviders(),t=[];for(let r of e)for(let o of r.models)t.push({...o,provider:r.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(ns),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",r=this.modeRegistry.getNext(t);return this.client.setMode(r),r}registerMode(e){this.modeRegistry.register(e)}forwardEvents(e){e instanceof Of&&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,r)=>this.emit("workflow:plan_decision",t,r)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:step_start",(t,r)=>this.emit("workflow:step_start",t,r)),e.on("workflow:step_complete",(t,r)=>this.emit("workflow:step_complete",t,r)),e.on("workflow:step_failed",(t,r,o)=>this.emit("workflow:step_failed",t,r,o)),e.on("workflow:step_retry",(t,r,o)=>this.emit("workflow:step_retry",t,r,o)),e.on("workflow:step_added",(t,r)=>this.emit("workflow:step_added",t,r)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,r)=>this.emit("workflow:completed",t,r)),e.on("workflow:failed",(t,r)=>this.emit("workflow:failed",t,r))}};l();import*as jf from"os";import*as Oe from"path";import*as Ze from"fs";var Ff=".toolpack",Lf="config",qf="toolpack.config.json";function nw(){return jf.homedir()}function sw(){return Oe.join(nw(),Ff)}function Uf(){return Oe.join(sw(),Lf)}function xr(){return Oe.join(Uf(),qf)}function iw(s=process.cwd()){return Oe.join(s,Ff)}function Wf(s=process.cwd()){return Oe.join(iw(s),Lf)}function Tr(s=process.cwd()){return Oe.join(Wf(s),qf)}function Gf(){let s=Uf();Ze.existsSync(s)||Ze.mkdirSync(s,{recursive:!0})}function KA(s=process.cwd()){let e=Wf(s);Ze.existsSync(e)||Ze.mkdirSync(e,{recursive:!0})}l();import*as J from"fs";import*as Pr from"path";function is(s,e){if(!e)return s;if(!s)return e;let t={...s};for(let r of Object.keys(e))e[r]instanceof Array?t[r]=e[r]:e[r]instanceof Object&&r in s?t[r]=is(s[r],e[r]):t[r]=e[r];return t}function ss(s){if(!J.existsSync(s))return null;try{let e=J.readFileSync(s,"utf-8");return JSON.parse(e)}catch{return null}}function ZA(s=process.cwd()){let e=Pr.join(s,"toolpack.config.json"),t=xr(),r=Tr(s),o=ss(e)||{},n=ss(t)||{},a=ss(r)||{},i=is(o,n);return i=is(i,a),i}function eM(s=process.cwd()){let e=Pr.join(s,"toolpack.config.json"),t=xr(),r=Tr(s),o=!J.existsSync(t),n=null,a="default";return J.existsSync(r)?(n=r,a="local"):J.existsSync(t)?(n=t,a="global"):J.existsSync(e)&&(n=e,a="base"),{isFirstRun:o,activeConfigPath:n,configSource:a}}function tM(s=process.cwd()){let e=xr();if(!J.existsSync(e)){Gf();let t=null,r=Tr(s);if(J.existsSync(r))t=r;else{let n=Pr.join(s,"toolpack.config.json");if(J.existsSync(n))t=n;else{let a=Rr();a&&J.existsSync(a)&&(t=a)}}let o={};if(t)try{let n=J.readFileSync(t,"utf-8");o=JSON.parse(n)}catch{}J.writeFileSync(e,JSON.stringify(o,null,4),"utf-8")}}l();export{Af as AGENT_MODE,os as AGENT_PLANNING_PROMPT,rs as AGENT_STEP_PROMPT,Ef as AGENT_WORKFLOW,io as AIClient,ao as AnthropicAdapter,ge as AuthenticationError,et as BM25SearchEngine,wr as BUILT_IN_MODES,Mf as CHAT_MODE,Nf as CHAT_WORKFLOW,Yy as CODING_PLANNING_PROMPT,Vy as CODING_STEP_PROMPT,Df as CODING_WORKFLOW,Lf as CONFIG_DIR_NAME,qf as CONFIG_FILE_NAME,ke as ConnectionError,Ve as DEFAULT_MODE_NAME,z as DEFAULT_TOOLS_CONFIG,tg as DEFAULT_TOOL_SEARCH_CONFIG,JN as DEFAULT_WORKFLOW,ns as DEFAULT_WORKFLOW_CONFIG,lo as GeminiAdapter,M as InvalidRequestError,Xt as McpClient,me as McpConnectionError,hr as McpTimeoutError,yr as McpToolManager,Zt as ModeRegistry,De as OllamaAdapter,lt as OllamaProvider,po as OpenAIAdapter,as as PageError,eo as Planner,Y as ProviderAdapter,F as ProviderError,he as RateLimitError,H as SDKError,to as StepExecutor,Ff as TOOLPACK_DIR_NAME,tt as TOOL_SEARCH_NAME,ls as TimeoutError,Fe as ToolDiscoveryCache,Vt as ToolRegistry,ot as ToolRouter,If as Toolpack,br as WorkflowExecutor,ur as cloudDeployTool,gr as cloudListTool,fr as cloudStatusTool,kf as cloudToolsProject,zt as codingFindSymbolTool,Qt as codingGetImportsTool,Kt as codingGetSymbolsTool,Zd as codingToolsProject,es as createMcpToolProject,Zy as createMode,zy as createToolProject,mr as dbCountTool,pr as dbDeleteTool,lr as dbInsertTool,sr as dbQueryTool,ir as dbSchemaTool,ar as dbTablesTool,yf as dbToolsProject,cr as dbUpdateTool,er as diffApplyTool,Zo as diffCreateTool,tr as diffPreviewTool,Gu as diffToolsProject,ts as disconnectMcpToolProject,Gf as ensureGlobalConfigDir,KA as ensureLocalConfigDir,Rt as execKillTool,Et as execListProcessesTool,kt as execReadOutputTool,_t as execRunBackgroundTool,St as execRunShellTool,vt as execRunTool,kl as execToolsProject,vs as fetchUrlAsBase64,mt as fsAppendFileTool,bt as fsCopyTool,ht as fsCreateDirTool,dt as fsDeleteFileTool,ut as fsExistsTool,gt as fsListDirTool,yt as fsMoveTool,xt as fsReadFileRangeTool,ct as fsReadFileTool,Pt as fsReplaceInFileTool,Tt as fsSearchTool,ft as fsStatTool,Ua as fsToolsProject,Ct as fsTreeTool,pt as fsWriteFileTool,Sr as generateToolCategoriesPrompt,gg as getDefaultSlmModel,Uf as getGlobalConfigDir,xr as getGlobalConfigPath,sw as getGlobalToolpackDir,Wf as getLocalConfigDir,Tr as getLocalConfigPath,iw as getLocalToolpackDir,xs as getMimeType,co as getOllamaBaseUrl,fg as getOllamaProviderEntries,yg as getRegisteredSlmModels,eM as getRuntimeConfigStatus,Cr as getToolSearchSchema,Er as getToolpackConfig,nw as getUserHomeDir,zo as gitAddTool,Qo as gitBlameTool,Vo as gitBranchCreateTool,Yo as gitBranchListTool,Xo as gitCheckoutTool,Ko as gitCommitTool,Jo as gitDiffTool,Ho as gitLogTool,Bo as gitStatusTool,ku as gitToolsProject,Lt as httpDeleteTool,qt as httpDownloadTool,It as httpGetTool,jt as httpPostTool,Ft as httpPutTool,Hc as httpToolsProject,tM as initializeGlobalConfigIfFirstRun,Ts as isDataUri,hg as isRegisteredSlm,vr as isToolSearchTool,Po as loadFullConfig,ZA as loadRuntimeConfig,Wt as loadToolsConfig,cg as normalizeImagePart,ne as ollamaRequest,Dr as ollamaStream,Ps as parseDataUri,Cs as readFileAsBase64,ug as reloadToolpackConfig,gh as saveToolsConfig,Mt as systemCwdTool,Ot as systemDiskUsageTool,Nt as systemEnvTool,Dt as systemInfoTool,At as systemSetEnvTool,cc as systemToolsProject,lg as toDataUri,Le as toolSearchDefinition,Jt as webExtractLinksTool,Ut as webFetchTool,Bt as webScrapeTool,Gt as webSearchTool,fm as webToolsProject};
|
|
503
|
+
`.trim(),s={...t,messages:[{role:"system",content:r},...t.messages]},i="";for await(let a of this.client.stream(s,o))a.delta&&(i+=a.delta),yield a;e.steps.forEach(a=>{a.status="completed",a.result={success:!0,output:i}}),e.status="completed",e.completedAt=new Date,this.emit("workflow:completed",e,{success:!0,plan:e,output:i,metrics:this.computeMetrics(e,e.startedAt.getTime(),0)})}waitForApproval(e){return new Promise(t=>{this.pendingApprovals.set(e,t)})}approvePlan(e){let t=this.pendingApprovals.get(e);t&&(t(!0),this.pendingApprovals.delete(e))}rejectPlan(e){let t=this.pendingApprovals.get(e);t&&(t(!1),this.pendingApprovals.delete(e))}};c();import{EventEmitter as dy}from"events";P();var uy=class n extends dy{client;activeProviderName;modeRegistry;workflowExecutor;knowledgeLayers=[];customProviderNames=new Set;mcpToolProject=null;constructor(e,t,o){super(),this.client=e,this.activeProviderName=t,this.modeRegistry=o;let r=this.client.getProvider(t);r&&this.forwardEvents(r),this.workflowExecutor=new Vr(this.client,mi,this.client.getQueryClassifier()),this.forwardWorkflowEvents()}buildKnowledgeRequestTools(){return this.knowledgeLayers.length===0?[]:this.knowledgeLayers.length===1?[this.knowledgeLayers[0].toTool(),{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async s=>({success:!0,id:await this.knowledgeLayers[0].add(s.content,s.metadata),message:"Content added to knowledge base successfully."})}]:[{name:"knowledge_search",displayName:"Knowledge Search",description:`Search across ${this.knowledgeLayers.length} knowledge layers for relevant information.`,category:"search",cacheable:!1,parameters:{type:"object",properties:{query:{type:"string",description:"Search query to find relevant information"},limit:{type:"number",description:"Maximum number of results to return (default: 10)"},threshold:{type:"number",description:"Minimum similarity threshold 0-1 (default: 0.7)"},filter:{type:"object",description:"Optional metadata filters"}},required:["query"]},execute:async o=>{let s=(await Promise.all(this.knowledgeLayers.map(async(a,l)=>(await a.toTool().execute({query:o.query,limit:o.limit,threshold:o.threshold,filter:o.filter})).map(d=>({...d,_layer:l}))))).flat();s.sort((a,l)=>(l.score??0)-(a.score??0));let i=o.limit??10;return s.slice(0,i)}},{name:"knowledge_add",displayName:"Add to Knowledge",description:"Add important new information to the primary knowledge base for future reference.",category:"knowledge",parameters:{type:"object",properties:{content:{type:"string",description:"The content to add to the knowledge base."},metadata:{type:"object",description:"Optional metadata such as source, category, or tags."}},required:["content"]},execute:async o=>({success:!0,id:await this.knowledgeLayers[0].add(o.content,o.metadata),message:"Content added to knowledge base successfully."})}]}prepareRequest(e){let t=[...this.buildKnowledgeRequestTools(),...e.requestTools||[]];if(t.length===0)return e;let o=new Map;for(let r of t)o.set(r.name,r);return{...e,requestTools:Array.from(o.values())}}static async init(e){let t=Zo(e.configPath);Di(t.logging);let o=new ko,r=yo(e.configPath);o.setConfig(r),e.tools&&await o.loadBuiltIn(),e.customTools&&await o.loadProjects(e.customTools);let s=null,i=e.mcp||t.mcp;if(i)try{C("[MCP] Initializing MCP tool integration");let $=await ai(i);s=$,await o.loadProjects([$]),C(`[MCP] Loaded ${$.tools.length} tools from MCP servers`)}catch($){ee(`[MCP] Failed to initialize MCP tools: ${$}`)}let a=t.systemPrompt,l=e.disableBaseContext||t.disableBaseContext||t.baseContext===!1||!1,p=t.modeOverrides||{},m={},d=new Set,g=e.defaultProvider||e.provider;if(e.providers)for(let[$,_]of Object.entries(e.providers)){let E=$===g,U=await n.createProvider($,_,e.configPath,!E);U&&(m[$]=U)}else if(e.provider){let $={apiKey:e.apiKey,model:e.model},_=await n.createProvider(e.provider,$,e.configPath,!1);_&&(m[e.provider]=_)}else if(!e.customProviders)throw new Error('No provider specified. Pass { provider: "name" }, { providers: { ... } }, or { customProviders: { ... } } to init().');if(e.customProviders){let $=Array.isArray(e.customProviders)?e.customProviders:Object.entries(e.customProviders).map(([_,E])=>(E.name=E.name||_,E));for(let _ of $){if(typeof _.generate!="function"||typeof _.stream!="function"||typeof _.embed!="function")throw new Error("Custom provider must implement the ProviderAdapter interface (generate, stream, embed methods). Import { ProviderAdapter } from 'toolpack' and implement or extend it.");let E=_.name;if(!E)throw new Error("Custom provider must have a 'name' property set. Set adapter.name in the constructor or use the record syntax: { 'provider-name': adapter }");if(m[E])throw new Error(`Custom provider name "${E}" conflicts with a built-in provider designation. Choose a different name.`);d.add(E),m[E]=_}}if(!g&&e.customProviders&&(g=(Array.isArray(e.customProviders)?e.customProviders[0]:Object.values(e.customProviders)[0])?.name),!g)throw new Error("No default provider specified.");let w=new $o;if(e.customModes)for(let $ of e.customModes)w.register($);let b={...p,...e.modeOverrides||{}};for(let[$,_]of Object.entries(b)){let E=w.get($);if(E){_.systemPrompt!==void 0&&(E.systemPrompt=_.systemPrompt),_.toolSearch&&(E.toolSearch={...E.toolSearch||{},..._.toolSearch});for(let[U,X]of Object.entries(_))U!=="systemPrompt"&&U!=="toolSearch"&&(E[U]=X)}}let T=t.hitl||{};e.confirmationMode!==void 0&&(T.confirmationMode=e.confirmationMode),T.enabled===void 0&&e.onToolConfirm&&(T.enabled=!0),T.confirmationMode===void 0&&e.onToolConfirm&&(T.confirmationMode="all");let x=new Oo({providers:m,defaultProvider:g,toolRegistry:o,toolsConfig:o.getConfig(),systemPrompt:a,disableBaseContext:l,hitlConfig:Object.keys(T).length>0?T:void 0,onToolConfirm:e.onToolConfirm,conversationId:e.conversationId,contextWindowConfig:e.contextWindow}),S=new n(x,g,w),v=e.knowledge,D=v==null?[]:Array.isArray(v)?v:[v];S.knowledgeLayers=D.filter($=>!!$&&typeof $.toTool=="function"),S.customProviderNames=d,S.mcpToolProject=s;let F=e.defaultMode||dt,k=w.get(F);return k&&(x.setMode(k),k.workflow&&S.workflowExecutor.setConfig(k.workflow)),S}static async createProvider(e,t,o,r=!1){if(["openai","anthropic","gemini","openrouter"].includes(e)){let s=`TOOLPACK_${e.toUpperCase()}_KEY`,i=t.apiKey||process.env[s]||process.env[`${e.toUpperCase()}_API_KEY`];if(!i){if(r)return null;throw new Error(`No API key found for '${e}'. Set ${s} or pass apiKey in config.`)}switch(e){case"openai":return new ot(i,t.baseUrl);case"anthropic":return new Io(i,t.baseUrl);case"gemini":return new Lo(i);case"openrouter":return new qo(i,{siteUrl:t.siteUrl,siteName:t.siteName})}}if(e==="ollama")return new $t({baseUrl:t.baseUrl||Fo(o)});if(e.startsWith("ollama-")){let s=t.model||e.replace(/^ollama-/,""),i=t.baseUrl||Fo(o);return new Be({model:s,baseUrl:i})}throw new Error(`Unknown provider type: ${e}`)}async generate(e,t){let o;typeof e=="string"?o={messages:[{role:"user",content:e}],model:""}:o=e,o=this.prepareRequest(o);let r=this.getMode();if(r?.workflow?.planning?.enabled||r?.workflow?.steps?.enabled){let s=await this.workflowExecutor.execute(o,t||this.activeProviderName),i=0,a=0,l=0,p={steps:[]};s.plan.planningResponse?.usage&&(i+=s.plan.planningResponse.usage.prompt_tokens,a+=s.plan.planningResponse.usage.completion_tokens||0,l+=s.plan.planningResponse.usage.total_tokens,p.planning=s.plan.planningResponse.usage);for(let d of s.plan.steps)if(d.status==="completed"&&d.result?.response?.usage){let g=d.result.response.usage;i+=g.prompt_tokens,a+=g.completion_tokens||0,l+=g.total_tokens,p.steps.push({stepNumber:d.number,description:d.description,usage:g})}let m={prompt_tokens:i,completion_tokens:a,total_tokens:l};return s.response?{...s.response,content:s.output||s.response.content||null,usage:m,usage_details:p}:{content:s.output||null,usage:m,usage_details:p}}return this.client.generate(o,t)}async*stream(e,t){let o=this.prepareRequest(e),r=this.getMode(),s=t||this.activeProviderName;if(r?.workflow?.planning?.enabled||r?.workflow?.steps?.enabled){yield*this.workflowExecutor.stream(o,s);return}yield*this.client.stream(o,t)}async embed(e,t){return this.client.embed(e,t)}setProvider(e){let t=this.client.getProvider(e);this.activeProviderName=e,this.client.setDefaultProvider(e),this.forwardEvents(t)}getProvider(){return this.client.getProvider(this.activeProviderName)}getClient(){return this.client}reloadConfig(e){let t=e||Ge();if(t)try{let o=Rt(t);o?.hitl&&this.client.updateHitlConfig(o.hitl)}catch(o){M(`[Toolpack] Failed to reload config from ${t}: ${o instanceof Error?o.message:String(o)}`)}}getWorkflowExecutor(){return this.workflowExecutor}async disconnect(){let e=this.getProvider();e&&"disconnect"in e&&await e.disconnect(),this.mcpToolProject&&await li(this.mcpToolProject)}async listProviders(){let e=this.client.getProviders(),t=[];for(let[o,r]of e.entries()){let s=this.customProviderNames.has(o),i=[];try{i=await r.getModels()}catch(a){M(`[Toolpack] Failed to fetch models for provider '${o}': ${a}`)}t.push({name:o,displayName:r.getDisplayName(),type:s?"custom":"built-in",models:i})}return t}async loadToolProject(e){let t=this.client.getToolRegistry();if(t)await t.loadProject(e);else throw new Error("No tool registry configured. Initialize Toolpack with tools enabled.")}async listModels(){let e=await this.listProviders(),t=[];for(let o of e)for(let r of o.models)t.push({...r,provider:o.name});return t}setMode(e){let t=this.modeRegistry.get(e);if(!t)throw new Error(`Mode "${e}" not found. Available modes: ${this.modeRegistry.getNames().join(", ")}`);return this.client.setMode(t),t.workflow?this.workflowExecutor.setConfig(t.workflow):this.workflowExecutor.setConfig(mi),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 dy&&e.on("status",t=>this.emit("status",t))}forwardWorkflowEvents(){let e=this.workflowExecutor;e.on("workflow:plan_created",t=>this.emit("workflow:plan_created",t)),e.on("workflow:plan_decision",(t,o)=>this.emit("workflow:plan_decision",t,o)),e.on("workflow:started",t=>this.emit("workflow:started",t)),e.on("workflow:step_start",(t,o)=>this.emit("workflow:step_start",t,o)),e.on("workflow:step_complete",(t,o)=>this.emit("workflow:step_complete",t,o)),e.on("workflow:step_failed",(t,o,r)=>this.emit("workflow:step_failed",t,o,r)),e.on("workflow:step_retry",(t,o,r)=>this.emit("workflow:step_retry",t,o,r)),e.on("workflow:step_added",(t,o)=>this.emit("workflow:step_added",t,o)),e.on("workflow:progress",t=>this.emit("workflow:progress",t)),e.on("workflow:completed",(t,o)=>this.emit("workflow:completed",t,o)),e.on("workflow:failed",(t,o)=>this.emit("workflow:failed",t,o))}};c();c();c();var Xr=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 di=class{lru;maxMessagesPerConversation;constructor(e={}){this.lru=new Xr(e.maxConversations??500),this.maxMessagesPerConversation=e.maxMessagesPerConversation??500}async append(e){let t=this.lru.get(e.conversationId);t||(t=[],this.lru.set(e.conversationId,t)),!t.some(o=>o.id===e.id)&&(t.push(e),t.sort((o,r)=>o.timestamp.localeCompare(r.timestamp)),t.length>this.maxMessagesPerConversation&&t.splice(0,t.length-this.maxMessagesPerConversation))}async get(e,t={}){let r=(this.lru.get(e)??[]).slice();if(t.scope!==void 0&&(r=r.filter(s=>s.scope===t.scope)),t.sinceTimestamp!==void 0&&(r=r.filter(s=>s.timestamp>=t.sinceTimestamp)),t.participantIds!==void 0&&t.participantIds.length>0){let s=new Set(t.participantIds);r=r.filter(i=>s.has(i.participant.id))}return t.limit!==void 0&&r.length>t.limit&&(r=r.slice(r.length-t.limit)),r}async search(e,t,o={}){let r=this.lru.get(e)??[],s=t.toLowerCase(),i=o.limit??10,a=o.tokenCap??2e3,l=r.filter(d=>d.content.toLowerCase().includes(s)).slice().reverse(),p=[],m=0;for(let d of l){if(p.length>=i)break;let g=Math.ceil(d.content.length/4);if(p.length>0&&m+g>a)break;p.push(d),m+=g}return p}async deleteMessages(e,t){let o=this.lru.get(e);if(!o||t.length===0)return;let r=new Set(t),s=o.filter(i=>!r.has(i.id));this.lru.set(e,s)}clearConversation(e){this.lru.set(e,[])}get conversationCount(){return this.lru.size}};c();import nx from"better-sqlite3";import*as ft from"fs";import*as Do from"path";function sx(){let n=Do.join(process.cwd(),".toolpack","db","conversation");return ft.existsSync(n)||ft.mkdirSync(n,{recursive:!0}),Do.join(n,"conversation.sqlite")}var ui=class{db;maxMessagesPerConversation;useFTS;constructor(e={}){let t=e.dbPath??sx(),o=Do.dirname(t);if(ft.existsSync(o)||ft.mkdirSync(o,{recursive:!0}),this.db=new nx(t),e.enableWAL!==!1){try{this.db.pragma("journal_mode = WAL")}catch{}try{this.db.pragma("synchronous = NORMAL")}catch{}}this.useFTS=e.useFTS===!0,this.maxMessagesPerConversation=e.maxMessagesPerConversation??500,this.initSchema()}initSchema(){this.db.exec(`
|
|
504
|
+
CREATE TABLE IF NOT EXISTS messages (
|
|
505
|
+
id TEXT NOT NULL,
|
|
506
|
+
conversation_id TEXT NOT NULL,
|
|
507
|
+
participant_kind TEXT,
|
|
508
|
+
participant_id TEXT,
|
|
509
|
+
participant_display_name TEXT,
|
|
510
|
+
content TEXT NOT NULL,
|
|
511
|
+
timestamp TEXT NOT NULL,
|
|
512
|
+
scope TEXT NOT NULL,
|
|
513
|
+
metadata TEXT,
|
|
514
|
+
PRIMARY KEY (conversation_id, id)
|
|
515
|
+
)`),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_conv_ts ON messages (conversation_id, timestamp)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_conv_scope_ts ON messages (conversation_id, scope, timestamp)"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_conv_participant_ts ON messages (conversation_id, participant_id, timestamp)"),this.useFTS&&(this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS messages_fts USING fts5(doc_key UNINDEXED, content, tokenize = 'unicode61')"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_messages_fts_key ON messages_fts (doc_key)"))}async append(e){let t=this.db.prepare(`INSERT OR IGNORE INTO messages (
|
|
516
|
+
id, conversation_id, participant_kind, participant_id, participant_display_name,
|
|
517
|
+
content, timestamp, scope, metadata
|
|
518
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),o=e.metadata?JSON.stringify(e.metadata):null,r=t.run(e.id,e.conversationId,e.participant.kind,e.participant.id,e.participant.displayName??null,e.content,e.timestamp,e.scope,o);if(this.useFTS&&r.changes>0){let s=`${e.conversationId}:${e.id}`;this.db.prepare("INSERT INTO messages_fts (doc_key, content) VALUES (?, ?)").run(s,e.content)}if(this.maxMessagesPerConversation>0){let a=this.db.prepare("SELECT COUNT(1) as c FROM messages WHERE conversation_id = ?").get(e.conversationId)?.c??0;if(a>this.maxMessagesPerConversation){let l=a-this.maxMessagesPerConversation,m=this.db.prepare("SELECT id FROM messages WHERE conversation_id = ? ORDER BY timestamp ASC LIMIT ?").all(e.conversationId,l).map(d=>d.id);if(m.length>0){let d=m.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${d})`).run(e.conversationId,...m),this.useFTS){let w=m.map(x=>`${e.conversationId}:${x}`),b=w.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${b})`).run(...w)}}}}}async get(e,t={}){let o=["conversation_id = ?"],r=[e];if(t.scope!==void 0&&(o.push("scope = ?"),r.push(t.scope)),t.sinceTimestamp!==void 0&&(o.push("timestamp >= ?"),r.push(t.sinceTimestamp)),t.participantIds&&t.participantIds.length>0){let p=t.participantIds.map(()=>"?").join(",");o.push(`participant_id IN (${p})`),r.push(...t.participantIds)}let i=`SELECT id, conversation_id, participant_kind, participant_id, participant_display_name, content, timestamp, scope, metadata FROM messages ${o.length?`WHERE ${o.join(" AND ")}`:""} ORDER BY timestamp ASC`,l=this.db.prepare(i).all(r).map(p=>this.rowToMessage(p));return t.limit!==void 0&&l.length>t.limit&&(l=l.slice(l.length-t.limit)),l}async search(e,t,o={}){let r=o.limit??10,s=o.tokenCap??2e3,i=[];this.useFTS?i=this.db.prepare(`
|
|
519
|
+
SELECT m.id, m.conversation_id, m.participant_kind, m.participant_id, m.participant_display_name,
|
|
520
|
+
m.content, m.timestamp, m.scope, m.metadata
|
|
521
|
+
FROM messages m
|
|
522
|
+
JOIN messages_fts f ON f.doc_key = (m.conversation_id || ':' || m.id)
|
|
523
|
+
WHERE m.conversation_id = ? AND f.content MATCH ?
|
|
524
|
+
ORDER BY m.timestamp DESC`).all(e,t):i=this.db.prepare(`
|
|
525
|
+
SELECT id, conversation_id, participant_kind, participant_id, participant_display_name,
|
|
526
|
+
content, timestamp, scope, metadata
|
|
527
|
+
FROM messages
|
|
528
|
+
WHERE conversation_id = ? AND content LIKE ? COLLATE NOCASE
|
|
529
|
+
ORDER BY timestamp DESC`).all(e,`%${t}%`);let a=i.map(m=>this.rowToMessage(m)),l=[],p=0;for(let m of a){if(l.length>=r)break;let d=Math.ceil(m.content.length/4);if(l.length>0&&p+d>s)break;l.push(m),p+=d}return l}async deleteMessages(e,t){if(!t||t.length===0)return;let o=t.map(()=>"?").join(",");if(this.db.prepare(`DELETE FROM messages WHERE conversation_id = ? AND id IN (${o})`).run(e,...t),this.useFTS){let s=t.map(l=>`${e}:${l}`),i=s.map(()=>"?").join(",");this.db.prepare(`DELETE FROM messages_fts WHERE doc_key IN (${i})`).run(...s)}}clearConversation(e){this.useFTS&&this.db.prepare("DELETE FROM messages_fts WHERE doc_key LIKE ?").run(`${e}:%`),this.db.prepare("DELETE FROM messages WHERE conversation_id = ?").run(e)}rowToMessage(e){return{id:e.id,conversationId:e.conversation_id,participant:{kind:e.participant_kind,id:e.participant_id,displayName:e.participant_display_name??void 0},content:e.content,timestamp:e.timestamp,scope:e.scope,metadata:e.metadata?JSON.parse(e.metadata):void 0}}close(){try{this.db.close()}catch{}}};c();import*as fy from"os";import*as Je from"path";import*as gt from"fs";var gy=".toolpack",hy="config",yy="toolpack.config.json";function ix(){return fy.homedir()}function ax(){return Je.join(ix(),gy)}function by(){return Je.join(ax(),hy)}function Yr(){return Je.join(by(),yy)}function lx(n=process.cwd()){return Je.join(n,gy)}function wy(n=process.cwd()){return Je.join(lx(n),hy)}function Zr(n=process.cwd()){return Je.join(wy(n),yy)}function Ty(){let n=by();gt.existsSync(n)||gt.mkdirSync(n,{recursive:!0})}function WF(n=process.cwd()){let e=wy(n);gt.existsSync(e)||gt.mkdirSync(e,{recursive:!0})}c();import*as V from"fs";import*as en from"path";function gi(n,e){if(!e)return n;if(!n)return e;let t={...n};for(let o of Object.keys(e))e[o]instanceof Array?t[o]=e[o]:e[o]instanceof Object&&o in n?t[o]=gi(n[o],e[o]):t[o]=e[o];return t}function fi(n){if(!V.existsSync(n))return null;try{let e=V.readFileSync(n,"utf-8");return JSON.parse(e)}catch{return null}}function HF(n=process.cwd()){let e=en.join(n,"toolpack.config.json"),t=Yr(),o=Zr(n),r=fi(e)||{},s=fi(t)||{},i=fi(o)||{},a=gi(r,s);return a=gi(a,i),a}function KF(n=process.cwd()){let e=en.join(n,"toolpack.config.json"),t=Yr(),o=Zr(n),r=!V.existsSync(t),s=null,i="default";return V.existsSync(o)?(s=o,i="local"):V.existsSync(t)?(s=t,i="global"):V.existsSync(e)&&(s=e,i="base"),{isFirstRun:r,activeConfigPath:s,configSource:i}}function JF(n=process.cwd()){let e=Yr();if(!V.existsSync(e)){Ty();let t=null,o=Zr(n);if(V.existsSync(o))t=o;else{let s=en.join(n,"toolpack.config.json");if(V.existsSync(s))t=s;else{let i=Ge();i&&V.existsSync(i)&&(t=i)}}let r={};if(t)try{let s=V.readFileSync(t,"utf-8");r=JSON.parse(s)}catch{}V.writeFileSync(e,JSON.stringify(r,null,4),"utf-8")}}c();export{cy as AGENT_MODE,ci as AGENT_PLANNING_PROMPT,pi as AGENT_STEP_PROMPT,iy as AGENT_WORKFLOW,Oo as AIClient,Io as AnthropicAdapter,Se as AuthenticationError,bt as BM25SearchEngine,Qr as BUILT_IN_MODES,py as CHAT_MODE,ly as CHAT_WORKFLOW,my as CODING_MODE,XT as CODING_PLANNING_PROMPT,YT as CODING_STEP_PROMPT,ay as CODING_WORKFLOW,hy as CONFIG_DIR_NAME,yy as CONFIG_FILE_NAME,qe as ConnectionError,bi as ContextWindowConfigError,tn as ContextWindowExceededError,cn as ContextWindowStateManager,wi as ConversationNotFoundError,dt as DEFAULT_MODE_NAME,Y as DEFAULT_TOOLS_CONFIG,qy as DEFAULT_TOOL_SEARCH_CONFIG,Sj as DEFAULT_WORKFLOW,mi as DEFAULT_WORKFLOW_CONFIG,Lo as GeminiAdapter,di as InMemoryConversationStore,on as InsufficientContextError,j as InvalidRequestError,Ro as McpClient,ve as McpConnectionError,Kr as McpTimeoutError,Jr as McpToolManager,$o as ModeRegistry,Be as OllamaAdapter,$t as OllamaProvider,ot as OpenAIAdapter,qo as OpenRouterAdapter,hi as PageError,_o as Planner,te as ProviderAdapter,W as ProviderError,ke as RateLimitError,A as SDKError,ui as SQLiteConversationStore,Eo as StepExecutor,rn as SummarizationError,gy as TOOLPACK_DIR_NAME,wt as TOOL_SEARCH_NAME,yi as TimeoutError,Xe as ToolDiscoveryCache,ko as ToolRegistry,xt as ToolRouter,uy as Toolpack,Vr as WorkflowExecutor,Zy as addBypassRule,Dx as buildSummarizedHistory,Br as cloudDeployTool,Hr as cloudListTool,zr as cloudStatusTool,ry as cloudToolsProject,vo as codingFindSymbolTool,Po as codingGetImportsTool,Co as codingGetSymbolsTool,_g as codingToolsProject,xi as countTokens,Ri as createContextWindowStateManager,ai as createMcpToolProject,ZT as createMode,Mx as createSummarizationReport,ln as createSummarySystemMessage,BT as createToolProject,Ur as dbCountTool,Wr as dbDeleteTool,Fr as dbInsertTool,Ir as dbQueryTool,Lr as dbSchemaTool,jr as dbTablesTool,Hh as dbToolsProject,qr as dbUpdateTool,Dr as diffApplyTool,Er as diffCreateTool,Mr as diffPreviewTool,wh as diffToolsProject,li as disconnectMcpToolProject,Ty as ensureGlobalConfigDir,WF as ensureLocalConfigDir,Ly as estimateSummaryTokens,Re as estimateTokenCount,Qt as execKillTool,Vt as execListProcessesTool,Jt as execReadOutputTool,Kt as execRunBackgroundTool,zt as execRunShellTool,Bt as execRunTool,Xc as execToolsProject,Ex as extractConversationKeypoints,zi as fetchUrlAsBase64,Dt as fsAppendFileTool,Ft as fsCopyTool,It as fsCreateDirTool,Mt as fsDeleteFileTool,Nt as fsExistsTool,Ot as fsListDirTool,Lt as fsMoveTool,qt as fsReadFileRangeTool,_t as fsReadFileTool,Ut as fsReplaceInFileTool,Wt as fsSearchTool,At as fsStatTool,pc as fsToolsProject,Gt as fsTreeTool,Et as fsWriteFileTool,Iy as generateSummarizationPrompt,pn as generateToolCategoriesPrompt,xx as getContextWindowPercentage,tb as getDefaultSlmModel,by as getGlobalConfigDir,Yr as getGlobalConfigPath,ax as getGlobalToolpackDir,wy as getLocalConfigDir,Zr as getLocalConfigPath,lx as getLocalToolpackDir,kx as getMessageStats,Wi as getMimeType,Fo as getOllamaBaseUrl,Yy as getOllamaProviderEntries,rb as getRegisteredSlmModels,KF as getRuntimeConfigStatus,vi as getSafeOutputReserve,Tt as getToolSearchSchema,gn as getToolpackConfig,ix as getUserHomeDir,Pr as gitAddTool,kr as gitBlameTool,$r as gitBranchCreateTool,Rr as gitBranchListTool,_r as gitCheckoutTool,Sr as gitCommitTool,vr as gitDiffTool,Cr as gitLogTool,xr as gitStatusTool,nh as gitToolsProject,lo as githubContentsGetTextTool,ao as githubGraphqlExecuteTool,uo as githubPrDiffGetTool,fo as githubPrFilesListTool,mo as githubPrReviewCommentsReplyTool,co as githubPrReviewThreadsListTool,po as githubPrReviewThreadsResolveTool,go as githubPrReviewsSubmitTool,xd as githubToolsProject,Sx as groupMessagesByRole,fx as handleContextWindowError,so as httpDeleteTool,io as httpDownloadTool,oo as httpGetTool,ro as httpPostTool,no as httpPutTool,gm as httpToolsProject,JF as initializeGlobalConfigIfFirstRun,ux as isContextWindowError,Ui as isDataUri,ob as isRegisteredSlm,Mo as isToolSearchTool,Zs as k8sApplyManifestTool,ei as k8sDeleteResourceTool,Xs as k8sDescribeTool,ri as k8sGetConfigMapTool,Ys as k8sGetLogsTool,si as k8sGetNamespacesTool,oi as k8sListDeploymentsTool,Vs as k8sListPodsTool,ti as k8sListServicesTool,ni as k8sSwitchContextTool,JT as k8sToolsProject,ii as k8sWaitForDeploymentTool,Zo as loadFullConfig,HF as loadRuntimeConfig,yo as loadToolsConfig,Nx as mergeSummarizationResults,Vy as normalizeImagePart,ge as ollamaRequest,yn as ollamaStream,Gi as parseDataUri,ki as parseSummarizationResponse,Si as prepareSummarizationRequest,Ci as pruneMessages,Bi as readFileAsBase64,hn as reloadToolpackConfig,eb as removeBypassRule,dw as saveToolsConfig,eo as systemCwdTool,to as systemDiskUsageTool,Yt as systemEnvTool,Xt as systemInfoTool,Zt as systemSetEnvTool,Mp as systemToolsProject,Qy as toDataUri,Ye as toolSearchDefinition,Px as truncateMessage,Pi as validateSummarizationResult,To as webExtractLinksTool,ho as webFetchTool,wo as webScrapeTool,bo as webSearchTool,Gu as webToolsProject,Tx as wouldExceedContextWindow};
|