@juspay/neurolink 9.56.0 → 9.56.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/CHANGELOG.md +6 -0
- package/dist/browser/neurolink.min.js +3 -3
- package/dist/core/redisConversationMemoryManager.js +5 -1
- package/dist/lib/core/redisConversationMemoryManager.js +5 -1
- package/dist/lib/utils/messageBuilder.js +3 -0
- package/dist/utils/messageBuilder.js +3 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
## [9.56.1](https://github.com/juspay/neurolink/compare/v9.56.0...v9.56.1) (2026-04-21)
|
|
2
|
+
|
|
3
|
+
### Bug Fixes
|
|
4
|
+
|
|
5
|
+
- **(context):** Add support to filter out empty content chunks ([5f13d91](https://github.com/juspay/neurolink/commit/5f13d919cb5342dce3c2796fa22436ad6aceb318))
|
|
6
|
+
|
|
1
7
|
## [9.56.0](https://github.com/juspay/neurolink/compare/v9.55.11...v9.56.0) (2026-04-20)
|
|
2
8
|
|
|
3
9
|
### Features
|
|
@@ -998,7 +998,7 @@ ${p}
|
|
|
998
998
|
`)}return{type:"xlsx",content:l,mimeType:t.mimeType,metadata:t.metadata}}}}catch(o){return g.warn(`[FileDetector] ExcelProcessor failed for ${n}, using fallback`,o instanceof Error?o.message:String(o)),{type:"xlsx",content:r.formatInformativePlaceholder("Spreadsheet",n,e,t,o),mimeType:t.mimeType,metadata:t.metadata}}return{type:"xlsx",content:r.formatInformativePlaceholder("Spreadsheet",n,e,t),mimeType:t.mimeType,metadata:t.metadata}}static async processDocxFile(e,t){let n=t.metadata.filename||"document",o=t.extension?.toLowerCase();try{if(o==="odt"){let{openDocumentProcessor:s}=await Promise.resolve().then(()=>(nZ(),rZ)),i=await s.processFile({id:n,name:n,mimetype:t.mimeType||"application/vnd.oasis.opendocument.text",size:e.length,buffer:e});if(i.success&&i.data)return{type:"docx",content:i.data.textContent||r.formatInformativePlaceholder("Document",n,e,t),mimeType:t.mimeType,metadata:t.metadata}}else if(o==="rtf"){let{rtfProcessor:s}=await Promise.resolve().then(()=>(M_e(),P_e)),i=await s.processFile({id:n,name:n,mimetype:t.mimeType||"application/rtf",size:e.length,buffer:e});if(i.success&&i.data)return{type:"docx",content:i.data.textContent||r.formatInformativePlaceholder("Document",n,e,t),mimeType:t.mimeType,metadata:t.metadata}}else{let{wordProcessor:s}=await Promise.resolve().then(()=>(cZ(),aZ)),i=await s.processFile({id:n,name:n,mimetype:t.mimeType||"application/vnd.openxmlformats-officedocument.wordprocessingml.document",size:e.length,buffer:e});if(i.success&&i.data)return{type:"docx",content:i.data.textContent||r.formatInformativePlaceholder("Document",n,e,t),mimeType:t.mimeType,metadata:t.metadata}}}catch(s){return g.warn(`[FileDetector] Document processor failed for ${n}, using fallback`,s instanceof Error?s.message:String(s)),{type:"docx",content:r.formatInformativePlaceholder("Document",n,e,t,s),mimeType:t.mimeType,metadata:t.metadata}}return{type:"docx",content:r.formatInformativePlaceholder("Document",n,e,t),mimeType:t.mimeType,metadata:t.metadata}}static async processPptxFile(e,t){let n=t.metadata.filename||"presentation";try{let{PptxProcessor:o}=await Promise.resolve().then(()=>(g$(),f$)),s=await o.extractText(e);if(s)return{type:"pptx",content:s,mimeType:t.mimeType,metadata:t.metadata}}catch(o){return g.warn(`[FileDetector] PptxProcessor failed for ${n}, using fallback`,o instanceof Error?o.message:String(o)),{type:"pptx",content:r.formatInformativePlaceholder("Presentation",n,e,t,o),mimeType:t.mimeType,metadata:t.metadata}}return{type:"pptx",content:r.formatInformativePlaceholder("Presentation",n,e,t),mimeType:t.mimeType,metadata:t.metadata}}static async processSvgAsText(e,t){try{let{processSvg:n}=await Promise.resolve().then(()=>(z_e(),$_e)),o=await n({id:"svg-file",name:t.metadata.filename||"image.svg",mimetype:"image/svg+xml",size:e.length,buffer:e});return o.success&&o.data?(g.info(`[FileDetector] SVG processed as text: ${t.metadata.filename||"image.svg"}`),{type:"svg",content:o.data.textContent,mimeType:"image/svg+xml",metadata:{confidence:t.metadata.confidence,size:e.length,filename:t.metadata.filename,extension:t.extension}}):(g.warn(`[FileDetector] SVG processor failed, returning safe empty SVG: ${o.error?.userMessage}`),{type:"svg",content:'<svg xmlns="http://www.w3.org/2000/svg"></svg>',mimeType:"image/svg+xml",metadata:{confidence:t.metadata.confidence,size:e.length,filename:t.metadata.filename,extension:t.extension}})}catch(n){return g.warn(`[FileDetector] SVG processor not available, returning safe empty SVG: ${n instanceof Error?n.message:String(n)}`),{type:"svg",content:'<svg xmlns="http://www.w3.org/2000/svg"></svg>',mimeType:"image/svg+xml",metadata:{confidence:t.metadata.confidence,size:e.length,filename:t.metadata.filename,extension:t.extension}}}}static async loadFromURL(e,t){let n=t?.maxSize||209715200,o=t?.timeout||r.DEFAULT_NETWORK_TIMEOUT,s=t?.maxRetries??B_e,i=t?.retryDelay??j_e;return QNt(async()=>{let a=await nT(e,{dispatcher:tT().compose(rT.redirect({maxRedirections:5})),method:"GET",headersTimeout:o,bodyTimeout:o});if(a.statusCode!==200)throw new Error(`HTTP ${a.statusCode}`);let l=[],u=0;for await(let d of a.body){if(u+=d.length,u>n)throw new Error(`File too large: ${cS(u)} (max: ${cS(n)})`);l.push(d)}return Buffer.concat(l)},{maxRetries:s,retryDelay:i})}static async loadFromPath(e,t){let n=t?.maxSize||209715200,o=await Lk(e);if(!o.isFile())throw new Error("Not a file");if(o.size>n)throw new Error(`File too large: ${cS(o.size)} (max: ${cS(n)})`);return await my(e)}static loadFromDataURI(e){let t=e.match(/^data:([^;]+);base64,(.+)$/);if(!t)throw new Error("Invalid data URI format");return Buffer.from(t[2],"base64")}},fZ=class{async detect(e){return Buffer.isBuffer(e)?this.isPNG(e)?this.result("image","image/png",95):this.isJPEG(e)?this.result("image","image/jpeg",95):this.isGIF(e)?this.result("image","image/gif",95):this.isWebP(e)?this.result("image","image/webp",95):this.isPDF(e)?this.result("pdf","application/pdf",95):e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?this.result("video","video/mp4",95):e.length>=4&&e[0]===26&&e[1]===69&&e[2]===223&&e[3]===163?this.result("video","video/x-matroska",90):e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===65&&e[9]===86&&e[10]===73&&e[11]===32?this.result("video","video/x-msvideo",95):e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===65&&e[10]===86&&e[11]===69?this.result("audio","audio/wav",95):e.length>=3&&e[0]===73&&e[1]===68&&e[2]===51?this.result("audio","audio/mpeg",95):e.length>=2&&e[0]===255&&(e[1]&224)===224?this.result("audio","audio/mpeg",80):e.length>=4&&e[0]===102&&e[1]===76&&e[2]===97&&e[3]===67?this.result("audio","audio/flac",95):e.length>=4&&e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?this.result("audio","audio/ogg",90):e.length>=4&&e[0]===80&&e[1]===75&&e[2]===3&&e[3]===4?this.result("archive","application/zip",70):e.length>=2&&e[0]===31&&e[1]===139?this.result("archive","application/gzip",90):e.length>=4&&e[0]===82&&e[1]===97&&e[2]===114&&e[3]===33?this.result("archive","application/x-rar-compressed",95):this.unknown():this.unknown()}isPNG(e){return e.length>=4&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71}isJPEG(e){return e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255}isGIF(e){return e.length>=4&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56}isWebP(e){return e.length>=12&&e.slice(0,4).toString()==="RIFF"&&e.slice(8,12).toString()==="WEBP"}isPDF(e){return e.length>=5&&e.slice(0,5).toString()==="%PDF-"}result(e,t,n){return{type:e,mimeType:t,extension:null,source:"buffer",metadata:{confidence:n}}}unknown(){return{type:"unknown",mimeType:"application/octet-stream",extension:null,source:"buffer",metadata:{confidence:0}}}},gZ=class{async detect(e){if(typeof e!="string"||!this.isURL(e))return this.unknown();try{let n=(await nT(e,{dispatcher:tT().compose(rT.redirect({maxRedirections:5})),method:"HEAD",headersTimeout:Bl.DEFAULT_HEAD_TIMEOUT,bodyTimeout:Bl.DEFAULT_HEAD_TIMEOUT})).headers["content-type"]||"",o=this.mimeToFileType(n);return{type:o,mimeType:n.split(";")[0].trim(),extension:null,source:"url",metadata:{confidence:o!=="unknown"?85:0}}}catch{return this.unknown()}}mimeToFileType(e){let t=e.toLowerCase().split(";")[0].trim();return t==="text/csv"||t==="text/tab-separated-values"?"csv":t==="image/svg+xml"?"svg":t.startsWith("image/")?"image":t==="application/pdf"?"pdf":t.startsWith("video/")?"video":t.startsWith("audio/")?"audio":t==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||t==="application/msword"?"docx":t==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||t==="application/vnd.ms-excel"?"xlsx":t==="application/vnd.openxmlformats-officedocument.presentationml.presentation"||t==="application/vnd.ms-powerpoint"?"pptx":t==="application/vnd.oasis.opendocument.text"?"docx":t==="application/vnd.oasis.opendocument.spreadsheet"?"xlsx":t==="application/vnd.oasis.opendocument.presentation"?"pptx":t==="application/rtf"||t==="text/rtf"?"docx":t==="application/zip"||t==="application/x-zip-compressed"||t==="application/gzip"||t==="application/x-gzip"||t==="application/x-tar"||t==="application/x-compressed-tar"||t==="application/java-archive"||t==="application/x-rar-compressed"||t==="application/vnd.rar"||t==="application/x-7z-compressed"?"archive":t==="text/plain"||t==="text/markdown"||t==="text/html"||t==="text/css"||t==="text/javascript"||t==="text/typescript"||t==="application/json"||t==="application/xml"||t==="text/xml"||t==="application/yaml"||t==="application/x-yaml"||t.startsWith("text/x-")||t.startsWith("text/")?"text":"unknown"}isURL(e){return e.startsWith("http://")||e.startsWith("https://")}unknown(){return{type:"unknown",mimeType:"application/octet-stream",extension:null,source:"buffer",metadata:{confidence:0}}}},hZ=class{async detect(e){if(typeof e!="string")return this.unknown();let t=this.getExtension(e);if(!t)return this.unknown();let o={csv:"csv",tsv:"csv",jpg:"image",jpeg:"image",png:"image",gif:"image",webp:"image",bmp:"image",tiff:"image",tif:"image",svg:"svg",avif:"image",pdf:"pdf",mp4:"video",mkv:"video",mov:"video",avi:"video",webm:"video",wmv:"video",flv:"video",mp3:"audio",wav:"audio",ogg:"audio",flac:"audio",m4a:"audio",aac:"audio",wma:"audio",opus:"audio",zip:"archive",tar:"archive",gz:"archive",tgz:"archive",rar:"archive","7z":"archive",jar:"archive",xlsx:"xlsx",xls:"xlsx",docx:"docx",doc:"docx",pptx:"pptx",ppt:"pptx",odt:"docx",ods:"xlsx",odp:"pptx",rtf:"docx",txt:"text",md:"text",markdown:"text",json:"text",xml:"text",yaml:"text",yml:"text",html:"text",htm:"text",css:"text",log:"text",conf:"text",cfg:"text",ini:"text",env:"text",toml:"text",properties:"text",gitignore:"text",dockerignore:"text",editorconfig:"text",prettierrc:"text",eslintrc:"text",babelrc:"text",js:"text",mjs:"text",cjs:"text",jsx:"text",ts:"text",tsx:"text",py:"text",java:"text",go:"text",rs:"text",rb:"text",php:"text",c:"text",cpp:"text",cc:"text",h:"text",hpp:"text",cs:"text",swift:"text",kt:"text",kts:"text",scala:"text",sh:"text",bash:"text",zsh:"text",ps1:"text",sql:"text",r:"text",lua:"text",pl:"text",perl:"text",dart:"text",ex:"text",exs:"text",erl:"text",hs:"text",clj:"text",lisp:"text",vim:"text",m4v:"video",ico:"image"}[t.toLowerCase()];return{type:o||"unknown",mimeType:this.getMimeType(t),extension:t,source:this.detectSource(e),metadata:{confidence:o?85:0}}}getExtension(e){if(this.isURL(e)){let o=new URL(e).pathname.match(/\.([^.]+)$/);return o?o[1]:null}let t=e.match(/\.([^.]+)$/);return t?t[1]:null}isURL(e){return e.startsWith("http://")||e.startsWith("https://")}detectSource(e){return e.startsWith("data:")?"datauri":this.isURL(e)?"url":"path"}getMimeType(e){return{csv:"text/csv",tsv:"text/tab-separated-values",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",bmp:"image/bmp",tiff:"image/tiff",tif:"image/tiff",svg:"image/svg+xml",avif:"image/avif",pdf:"application/pdf",mp4:"video/mp4",mkv:"video/x-matroska",mov:"video/quicktime",avi:"video/x-msvideo",webm:"video/webm",wmv:"video/x-ms-wmv",flv:"video/x-flv",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",flac:"audio/flac",m4a:"audio/mp4",aac:"audio/aac",wma:"audio/x-ms-wma",opus:"audio/opus",zip:"application/zip",tar:"application/x-tar",gz:"application/gzip",tgz:"application/gzip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",jar:"application/java-archive",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xls:"application/vnd.ms-excel",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",doc:"application/msword",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",ppt:"application/vnd.ms-powerpoint",odt:"application/vnd.oasis.opendocument.text",ods:"application/vnd.oasis.opendocument.spreadsheet",odp:"application/vnd.oasis.opendocument.presentation",rtf:"application/rtf",txt:"text/plain",md:"text/markdown",markdown:"text/markdown",json:"application/json",xml:"application/xml",yaml:"application/yaml",yml:"application/yaml",html:"text/html",htm:"text/html",css:"text/css",log:"text/plain",conf:"text/plain",cfg:"text/plain",ini:"text/plain",env:"text/plain",toml:"text/plain",properties:"text/plain",gitignore:"text/plain",dockerignore:"text/plain",editorconfig:"text/plain",prettierrc:"application/json",eslintrc:"application/json",babelrc:"application/json",js:"text/javascript",mjs:"text/javascript",cjs:"text/javascript",jsx:"text/javascript",ts:"text/typescript",tsx:"text/typescript",py:"text/x-python",java:"text/x-java-source",go:"text/x-go",rs:"text/x-rustsrc",rb:"text/x-ruby",php:"text/x-php",c:"text/x-c",cpp:"text/x-c++",cc:"text/x-c++",h:"text/x-c",hpp:"text/x-c++",cs:"text/x-csharp",swift:"text/x-swift",kt:"text/x-kotlin",kts:"text/x-kotlin",scala:"text/x-scala",sh:"text/x-shellscript",bash:"text/x-shellscript",zsh:"text/x-shellscript",ps1:"text/x-powershell",sql:"text/x-sql",r:"text/x-r",lua:"text/x-lua",pl:"text/x-perl",perl:"text/x-perl",dart:"text/x-dart",ex:"text/x-elixir",exs:"text/x-elixir",erl:"text/x-erlang",hs:"text/x-haskell",clj:"text/x-clojure",lisp:"text/x-lisp",vim:"text/plain",m4v:"video/mp4",ico:"image/x-icon"}[e.toLowerCase()]||"application/octet-stream"}unknown(){return{type:"unknown",mimeType:"application/octet-stream",extension:null,source:"buffer",metadata:{confidence:0}}}},yZ=class{async detect(e){let t;if(Buffer.isBuffer(e))t=e;else if(typeof e=="string")if(e.startsWith("data:")){let o=e.match(/^data:([^;]+);base64,(.+)$/);if(!o)return this.unknown();t=Buffer.from(o[2],"base64")}else{if(e.startsWith("http://")||e.startsWith("https://"))return this.unknown();try{t=await my(e)}catch{return this.unknown()}}else return this.unknown();let n=t.toString("utf-8",0,Math.min(2e3,t.length));if(this.looksLikeJSON(n))return this.result("text","application/json",75);if(this.looksLikeCSV(n))return this.result("csv","text/csv",75);if(this.looksLikeXML(n)){let o=n.includes("<!DOCTYPE html")||n.includes("<html");return this.result("text",o?"text/html":"application/xml",70)}return this.looksLikeYAML(n)?this.result("text","application/yaml",70):this.looksLikeText(n)?this.result("text","text/plain",60):this.unknown()}looksLikeCSV(e){let t=e.trim().split(`
|
|
999
999
|
`);if(t.length<2)return!1;let n=t[0],s=[",",";"," ","|"].find(d=>n.includes(d));if(!s){if(e.startsWith("---")||/^[\s]*-\s+/m.test(e)||/^[\s]*[a-zA-Z_][a-zA-Z0-9_-]*:\s*/m.test(e)||e.startsWith("<")||e.includes("<?xml")||e.startsWith("{")&&e.includes("}")||e.startsWith("[")&&e.includes("]")||t.some(S=>S.trim().split(/\s+/).length>4))return!1;let p=t.every(S=>S.length>0&&S.length<1e3),m=!e.includes("\0"),f=t.map(S=>S.length),h=f.reduce((S,w)=>S+w,0)/f.length,y=f.reduce((S,w)=>S+(w-h)**2,0)/f.length,b=Math.sqrt(y)/h<.75;return p&&m&&b}let i=s==="|"?/\|/g:new RegExp(s,"g"),a=t.map(d=>(d.match(i)||[]).length),l=a[0];return a.filter(d=>d===l).length/t.length>=.8}looksLikeJSON(e){return eDt(e)}looksLikeXML(e){let t=e.trim();if(t.startsWith("<?xml")||t.includes("<!DOCTYPE html")||t.toLowerCase().includes("<html"))return!0;if(!t.startsWith("<")||!/<[a-zA-Z][a-zA-Z0-9-]*(?:\s[^>]*)?>/.test(t))return!1;let o=/<\/[a-zA-Z][a-zA-Z0-9-]*>/.test(t),s=/<[a-zA-Z][a-zA-Z0-9-]*(?:\s[^>]*)?\s*\/\s*>/.test(t);return o||s}looksLikeYAML(e){let t=e.trim();if(t.length===0)return!1;let n=t.split(`
|
|
1000
1000
|
`);if(n.length===1)return t==="---"||t==="...";let o=[];o.push(t.startsWith("---")),o.push(/^\.\.\.$|[\n]\.\.\.$/.test(t)),o.push(/^[\s]*-\s+[^-]/m.test(t));let s=/^[\s]*[a-zA-Z_][a-zA-Z0-9_-]*:\s*(.+)$/,i=n.filter(p=>s.test(p)).length;o.push(i>=2);let a=!1,l=n.slice(0,10);for(let p=0;p<l.length-1;p++){let m=l[p].trim(),f=l[p+1];if(m.length>0&&f.length>0&&/[:-]$/.test(m)){let h=l[p].match(/^[\s]*/)?.[0].length??0;if((f.match(/^[\s]*/)?.[0].length??0)>h){a=!0;break}}}o.push(a),o.push(/^\s*#\s+/m.test(t));let u=n.filter(p=>/^[\s]*-[\s]/.test(p)).length;return o.push(u>=2),o.push(/{\s*[a-zA-Z_]/.test(t)||/\[.*\]/.test(t)),o.filter(Boolean).length>=2}looksLikeText(e){if(e.includes("\0"))return!1;let t=0;for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);(o>=32&&o<127||o===9||o===10||o===13||o>127)&&t++}return t/e.length>=.85}result(e,t,n){return{type:e,mimeType:t,extension:null,source:"buffer",metadata:{confidence:n}}}unknown(){return{type:"unknown",mimeType:"application/octet-stream",extension:null,source:"buffer",metadata:{confidence:0}}}}});function q_e(r){return r?tDt[r]??1:1}function mr(r,e,t){if(!r||r.length===0)return 0;let n=t?3:4,o=Math.ceil(r.length/n),s=q_e(e),i=o*s,a=o*.05;return Math.ceil(i+a)}function rDt(r,e){let t="";if(r.content)if(typeof r.content=="string")t=r.content;else try{t=JSON.stringify(r.content)}catch{t=String(r.content)}return mr(t,e)+4}function Pn(r,e){return!r||r.length===0?0:r.reduce((n,o)=>n+rDt(o,e),0)+24}function y$(r,e,t){if(mr(r,t)<=e)return{text:r,truncated:!1};let o=q_e(t)+.05,s=Math.floor(e/o*4);if(s<=0)return{text:"",truncated:!0};let i=r.slice(0,s),a=Math.max(i.lastIndexOf(". "),i.lastIndexOf("! "),i.lastIndexOf("? "),i.lastIndexOf(`
|
|
1001
|
-
`)),l=a>s*.5?a+1:s;return{text:r.slice(0,l)+"...",truncated:!0}}var tDt,gc=A(()=>{"use strict";tDt={anthropic:1.23,"google-ai":1.18,vertex:1.18,mistral:1.26,openai:1,azure:1,bedrock:1.23,ollama:1,litellm:1,huggingface:1,sagemaker:1}});function sDt(r){let e=r.split("?")[0].split("#")[0],t=e.lastIndexOf(".");if(t===-1)return;let n=e.slice(t+1).toLowerCase();return oDt[n]}function iDt(r){if(!(r.length<4)){if(r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71||r[0]===255&&r[1]===216&&r[2]===255||r[0]===71&&r[1]===73&&r[2]===70||r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80)return"image";if(r[0]===37&&r[1]===80&&r[2]===68&&r[3]===70)return"pdf";if(r.length>=8&&r[4]===102&&r[5]===116&&r[6]===121&&r[7]===112||r[0]===26&&r[1]===69&&r[2]===223&&r[3]===163||r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===65&&r[9]===86&&r[10]===73&&r[11]===32)return"video";if(r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===65&&r[10]===86&&r[11]===69||r[0]===73&&r[1]===68&&r[2]===51||r[0]===102&&r[1]===76&&r[2]===97&&r[3]===67||r[0]===79&&r[1]===103&&r[2]===103&&r[3]===83)return"audio";if(r[0]===80&&r[1]===75&&r[2]===3&&r[3]===4||r[0]===31&&r[1]===139||r[0]===82&&r[1]===97&&r[2]===114&&r[3]===33)return"archive"}}function G_e(r){return typeof r=="object"&&!Buffer.isBuffer(r)&&"data"in r}function aDt(r){return G_e(r)?r.data:r}function V_e(r){if(G_e(r))return r.altText}function cDt(r){return r.role==="user"||r.role==="assistant"||r.role==="system"?{role:r.role,content:r.content}:null}function v$(r){let e=[];if(r.rowCount!==void 0&&e.push(`${r.rowCount} data rows`),r.columnCount!==void 0&&e.push(`${r.columnCount} columns`),r.columnNames&&r.columnNames.length>0){let t=r.columnNames.join(", ");e.push(`Columns: [${t}]`)}return r.hasEmptyColumns&&e.push("\u26A0\uFE0F Contains empty column names"),e.length>0?`**Metadata**: ${e.join(" | ")}`:""}function H_e(r){return!!r.schema&&(r.output?.format==="json"||r.output?.format==="structured")}function W_e(r,e){if(!g.shouldLog("debug"))return;let t={},n=0;for(let o of r){let s=typeof o.content=="string"?o.content.length:0;t[o.role]=(t[o.role]||0)+1,n+=s}g.debug("[MessageBuilder] Composed",{requestId:e,totalMessages:r.length,roles:t,totalChars:n,estimatedTokens:Math.ceil(n/4)})}async function x$(r){let e=[],t=r.conversationMessages&&r.conversationMessages.length>0,n=r.systemPrompt?.trim()||"";if(t&&(n=`${n.trim()}${U8}`),H_e(r)&&(n=`${n.trim()}${$8}`),n.trim()&&e.push({role:"system",content:n.trim(),providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}),t&&r.conversationMessages)for(let i of r.conversationMessages){let a=cDt(i);a&&e.push(a)}let o;if("prompt"in r&&r.prompt?o=r.prompt:"input"in r&&r.input?.text&&(o=r.input.text),"input"in r&&r.input){let i=r.input,a="",l="csvOptions"in r?r.csvOptions:void 0;if(i.csvFiles&&i.csvFiles.length>0)for(let u=0;u<i.csvFiles.length;u++){let d=i.csvFiles[u],p=dg(d,u),m=typeof d=="string"?d:p;try{let f=await Bl.detectAndProcess(d,{allowedTypes:["csv"],csvOptions:l}),h=`
|
|
1001
|
+
`)),l=a>s*.5?a+1:s;return{text:r.slice(0,l)+"...",truncated:!0}}var tDt,gc=A(()=>{"use strict";tDt={anthropic:1.23,"google-ai":1.18,vertex:1.18,mistral:1.26,openai:1,azure:1,bedrock:1.23,ollama:1,litellm:1,huggingface:1,sagemaker:1}});function sDt(r){let e=r.split("?")[0].split("#")[0],t=e.lastIndexOf(".");if(t===-1)return;let n=e.slice(t+1).toLowerCase();return oDt[n]}function iDt(r){if(!(r.length<4)){if(r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71||r[0]===255&&r[1]===216&&r[2]===255||r[0]===71&&r[1]===73&&r[2]===70||r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80)return"image";if(r[0]===37&&r[1]===80&&r[2]===68&&r[3]===70)return"pdf";if(r.length>=8&&r[4]===102&&r[5]===116&&r[6]===121&&r[7]===112||r[0]===26&&r[1]===69&&r[2]===223&&r[3]===163||r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===65&&r[9]===86&&r[10]===73&&r[11]===32)return"video";if(r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===65&&r[10]===86&&r[11]===69||r[0]===73&&r[1]===68&&r[2]===51||r[0]===102&&r[1]===76&&r[2]===97&&r[3]===67||r[0]===79&&r[1]===103&&r[2]===103&&r[3]===83)return"audio";if(r[0]===80&&r[1]===75&&r[2]===3&&r[3]===4||r[0]===31&&r[1]===139||r[0]===82&&r[1]===97&&r[2]===114&&r[3]===33)return"archive"}}function G_e(r){return typeof r=="object"&&!Buffer.isBuffer(r)&&"data"in r}function aDt(r){return G_e(r)?r.data:r}function V_e(r){if(G_e(r))return r.altText}function cDt(r){return r.role==="user"||r.role==="assistant"||r.role==="system"?r.content.trim()===""?null:{role:r.role,content:r.content}:null}function v$(r){let e=[];if(r.rowCount!==void 0&&e.push(`${r.rowCount} data rows`),r.columnCount!==void 0&&e.push(`${r.columnCount} columns`),r.columnNames&&r.columnNames.length>0){let t=r.columnNames.join(", ");e.push(`Columns: [${t}]`)}return r.hasEmptyColumns&&e.push("\u26A0\uFE0F Contains empty column names"),e.length>0?`**Metadata**: ${e.join(" | ")}`:""}function H_e(r){return!!r.schema&&(r.output?.format==="json"||r.output?.format==="structured")}function W_e(r,e){if(!g.shouldLog("debug"))return;let t={},n=0;for(let o of r){let s=typeof o.content=="string"?o.content.length:0;t[o.role]=(t[o.role]||0)+1,n+=s}g.debug("[MessageBuilder] Composed",{requestId:e,totalMessages:r.length,roles:t,totalChars:n,estimatedTokens:Math.ceil(n/4)})}async function x$(r){let e=[],t=r.conversationMessages&&r.conversationMessages.length>0,n=r.systemPrompt?.trim()||"";if(t&&(n=`${n.trim()}${U8}`),H_e(r)&&(n=`${n.trim()}${$8}`),n.trim()&&e.push({role:"system",content:n.trim(),providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}),t&&r.conversationMessages)for(let i of r.conversationMessages){let a=cDt(i);a&&e.push(a)}let o;if("prompt"in r&&r.prompt?o=r.prompt:"input"in r&&r.input?.text&&(o=r.input.text),"input"in r&&r.input){let i=r.input,a="",l="csvOptions"in r?r.csvOptions:void 0;if(i.csvFiles&&i.csvFiles.length>0)for(let u=0;u<i.csvFiles.length;u++){let d=i.csvFiles[u],p=dg(d,u),m=typeof d=="string"?d:p;try{let f=await Bl.detectAndProcess(d,{allowedTypes:["csv"],csvOptions:l}),h=`
|
|
1002
1002
|
|
|
1003
1003
|
## CSV Data from "${p}":
|
|
1004
1004
|
`;if(f.metadata){let y=v$(f.metadata);y&&(h+=y+`
|
|
@@ -2164,12 +2164,12 @@ For "closing" slides (shows checkmarks \u2713):
|
|
|
2164
2164
|
- For regular content \u2192 type="content" (disc bullets \u2022)
|
|
2165
2165
|
|
|
2166
2166
|
\u26A0\uFE0F CRITICAL: Content MUST fit within slide box. Keep text SHORT.`;DQt=5,LQt=50,FQt=10,UQt=5e3,$Qt=Object.keys(jB),zQt=["business","students","technical","general"],BQt=["professional","casual","educational","persuasive"],jQt=["16:9","4:3"],$ee={content:{bulletStyle:"disc",baseFontSize:18},bullets:{bulletStyle:"disc",baseFontSize:18},agenda:{bulletStyle:"number",baseFontSize:18},"numbered-list":{bulletStyle:"number",baseFontSize:18},conclusion:{bulletStyle:"checkmark",baseFontSize:18},closing:{bulletStyle:"checkmark",baseFontSize:18},"two-column":{bulletStyle:"disc",baseFontSize:16},"three-column":{bulletStyle:"disc",baseFontSize:14},"split-content":{bulletStyle:"disc",baseFontSize:16},comparison:{bulletStyle:"arrow",baseFontSize:16},features:{bulletStyle:"none",baseFontSize:16},icons:{bulletStyle:"none",baseFontSize:16},default:{bulletStyle:"disc",baseFontSize:18}};Hee=6e4,VB=3e4,Wee=5,Kl=3e5});var pl,ki,GB=A(()=>{"use strict";bt();pl={PLANNING_FAILED:"PPT_PLANNING_FAILED",INVALID_AI_RESPONSE:"PPT_INVALID_AI_RESPONSE",IMAGE_GENERATION_FAILED:"PPT_IMAGE_GENERATION_FAILED",ASSEMBLY_FAILED:"PPT_ASSEMBLY_FAILED",FILE_WRITE_FAILED:"PPT_FILE_WRITE_FAILED",INVALID_INPUT:"PPT_INVALID_INPUT",TIMEOUT:"PPT_TIMEOUT"},ki=class extends Je{constructor(e,t,n,o){super({code:t,message:e,category:"execution",severity:"high",retriable:!1,context:{...n,originalMessage:o?.message},originalError:o}),this.name="PPTError"}}});var n1e={};le(n1e,{PPT_VALID_PROVIDERS:()=>BA,bufferToDataUrl:()=>Ow,calculateFontSize:()=>ete,createFormattedTextProps:()=>Lv,ensureOutputDirectory:()=>Zee,extractPPTContext:()=>qQt,generateOutputPath:()=>Jee,getEffectivePPTProvider:()=>VQt,getFailureStage:()=>HB,getLayoutName:()=>Yee,hasMarkdownFormatting:()=>Dv,isLogoConfig:()=>r1e,isObject:()=>t1e,normalizeLogoConfig:()=>Xee,parseMarkdownText:()=>Nv,toError:()=>Qee,validateImageBuffer:()=>WB});function qQt(r){let e=r.output?.ppt;if(!e)throw new ki("PPT options are required when mode is 'ppt'",pl.INVALID_INPUT,{field:"output.ppt"});let t;if(e.logoPath){if(Buffer.isBuffer(e.logoPath)||typeof e.logoPath=="string")t=e.logoPath;else if(typeof e.logoPath=="object"&&"data"in e.logoPath){let o=e.logoPath.data;t=Buffer.isBuffer(o)||typeof o=="string"?o:void 0}}let n=[];if(r.input?.images){for(let o of r.input.images)if(Buffer.isBuffer(o)||typeof o=="string")n.push(o);else if(typeof o=="object"&&"data"in o){let s=o.data;(Buffer.isBuffer(s)||typeof s=="string")&&n.push(s)}}return!t&&n.length>0&&(t=n[0]),{topic:r.input?.text||"",pages:e.pages,theme:e.theme??"AI will decide",audience:e.audience??"AI will decide",tone:e.tone??"AI will decide",generateAIImages:e.generateAIImages??!1,aspectRatio:e.aspectRatio||"16:9",outputPath:e.outputPath,logo:t,images:n.length>0?n:void 0,provider:r.provider,model:r.model}}async function VQt(r,e,t,n){let{ErrorFactory:o}=await Promise.resolve().then(()=>(bt(),XC)),s=e.toLowerCase();if(BA.includes(s)){let i=r,a=t||i?.modelName||i?.getDefaultModel?.()||"";return g.debug("[PPT Utils] Current provider is valid for PPT",{provider:e,model:a}),{provider:r,providerName:e,modelName:a,wasAutoSelected:!1}}g.info("[PPT Utils] Current provider not valid for PPT, auto-selecting",{currentProvider:e});for(let i of BA)if(j2(i)){g.info("[PPT Utils] Auto-selected PPT provider",{originalProvider:e,selectedProvider:i});let{AIProviderFactory:a}=await Promise.resolve().then(()=>(Gc(),q2)),{withTimeout:l}=await Promise.resolve().then(()=>(bt(),XC)),{PPT_GENERATION_TIMEOUT_MS:u}=await Promise.resolve().then(()=>(Ov(),Kee)),d=await l(a.createProvider(i,void 0,!0,n),u/4,o.toolTimeout("createProvider",u/4));return{provider:d,providerName:i,modelName:d.modelName,wasAutoSelected:!0}}throw o.invalidParameters("ppt-generation",new Error(`No PPT-compatible provider available. Configure one of: ${BA.join(", ")}`),{currentProvider:e,validProviders:BA})}function Jee(r){let e=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19),n=`${r.topic.substring(0,30).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase()}_${e}.pptx`;return r.outputPath?r.outputPath.endsWith(".pptx")?r.outputPath:or(r.outputPath,n):or(process.cwd(),"output",n)}async function Zee(r){let e=wC(r);try{let{withTimeout:t,ErrorFactory:n}=await Promise.resolve().then(()=>(bt(),XC)),{PPT_GENERATION_TIMEOUT_MS:o}=await Promise.resolve().then(()=>(Ov(),Kee));await t(q8(e,{recursive:!0}),o/8,n.toolTimeout("mkdirOutputDirectory",o/8))}catch(t){let n=t instanceof Error?t:new Error(String(t));throw new ki(`Failed to create output directory: ${e}`,pl.FILE_WRITE_FAILED,{directory:e},n)}}function t1e(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function r1e(r){return t1e(r)?"data"in r&&(Buffer.isBuffer(r.data)||typeof r.data=="string"):!1}function Xee(r){return r===null?null:Buffer.isBuffer(r)||typeof r=="string"?{data:r,position:"bottom-right",width:1,height:.4,showOn:"all-slides"}:r1e(r)?r:null}function Yee(r){switch(r){case"16:9":return"LAYOUT_16x9";case"4:3":return"LAYOUT_4x3";default:return"LAYOUT_16x9"}}function Qee(r){return r instanceof Error?r:new Error(String(r))}function HB(r){return r.contentPlan===null?"content-planning":r.slides===null?"slide-generation":r.outputPath===null?"pptx-assembly":"file-output"}function WB(r){return!r||r.length===0?{isValid:!1,mimeType:"",format:"",error:"Empty or undefined buffer"}:r.length<100?{isValid:!1,mimeType:"",format:"",error:`Buffer too small (${r.length} bytes)`}:r[0]===255&&r[1]===216&&r[2]===255?{isValid:!0,mimeType:"image/jpeg",format:"JPEG"}:r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?{isValid:!0,mimeType:"image/png",format:"PNG"}:r[0]===71&&r[1]===73&&r[2]===70?{isValid:!0,mimeType:"image/gif",format:"GIF"}:r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r.length>12&&r.slice(8,12).toString()==="WEBP"?{isValid:!0,mimeType:"image/webp",format:"WebP"}:r[0]===66&&r[1]===77?{isValid:!0,mimeType:"image/bmp",format:"BMP"}:{isValid:!1,mimeType:"image/png",format:"unknown",error:`Unknown format (magic bytes: ${r.slice(0,4).toString("hex")})`}}function Ow(r){let e=WB(r);return!e.isValid&&e.format===""?(g.warn("[bufferToDataUrl] Invalid image buffer",{error:e.error}),null):`data:${e.mimeType||"image/png"};base64,${r.toString("base64")}`}function Nv(r){if(!r||typeof r!="string")return[{text:r||""}];let e=[],t=/(\*\*\*(.+?)\*\*\*|\*\*(.+?)\*\*|\*(.+?)\*)/g,n=0;for(;;){let o=t.exec(r);if(o===null)break;o.index>n&&e.push({text:r.slice(n,o.index)}),o[2]?e.push({text:o[2],bold:!0,italic:!0}):o[3]?e.push({text:o[3],bold:!0}):o[4]&&e.push({text:o[4],italic:!0}),n=t.lastIndex}return n<r.length&&e.push({text:r.slice(n)}),e.length===0&&e.push({text:r}),e}function Dv(r){return!r||typeof r!="string"?!1:/\*{1,3}[^*]+\*{1,3}/.test(r)}function Lv(r,e){return r.map(t=>({text:t.text,options:{fontSize:e.fontSize,fontFace:e.fontFace,color:e.color,bold:t.bold||e.baseBold||!1,italic:t.italic||!1}}))}function ete(r,e=18){return r<=5?e:r<=7?Math.max(12,e-2):r<=10?Math.max(12,e-4):12}var BA,KB=A(()=>{"use strict";Pu();Kr();Im();Q();GB();BA=["vertex","openai","azure","anthropic","google-ai","bedrock"]});function HQt(r,e,t=!1){let n=e/72,o=.42,s=t?1.1:1,i=n*o*s;return r.length*i}function Ri(r,e,t,n=!0){if(r.addText(e,{x:Nt.title.x,y:Nt.title.y,w:Nt.title.w,h:Nt.title.h,fontSize:t.fonts.sizes.heading,fontFace:t.fonts.heading,color:t.colors.text.replace("#",""),bold:!0,fit:kt}),n){let o=HQt(e,t.fonts.sizes.heading,!0),s=Nt.title.w,a=Math.min(s,Math.max(1,o));r.addShape("rect",{x:Nt.title.x,y:Nt.title.y+Nt.title.h+.1,w:a,h:.03,fill:{color:t.colors.primary.replace("#","")}})}}function o1e(r){let{slide:e,bullets:t,startX:n,startY:o,width:s,theme:i,itemSpacing:a=.45}=r;if(!t||t.length===0)return;let l=Math.max(a,jA*2);t.forEach((u,d)=>{if(!u||!u.text)return;let p=u.bold||u.emphasis||!1,m=u.color?.replace("#","")||i.colors.text.replace("#","");if(Dv(u.text)){let f=Nv(u.text),h=[{text:"\u2022 ",options:{fontSize:i.fonts.sizes.body,fontFace:i.fonts.body,color:m}},...Lv(f,{fontSize:i.fonts.sizes.body,fontFace:i.fonts.body,color:m,baseBold:p})];e.addText(h,{x:n,y:o+d*l,w:s,h:Math.max(.4,l-jA),fit:kt})}else{let f=`\u2022 ${u.text}`;e.addText(f,{x:n,y:o+d*l,w:s,h:Math.max(.4,l-jA),fontSize:i.fonts.sizes.body,fontFace:i.fonts.body,color:m,bold:p,fit:kt})}})}function s1e(r,e,t,n,o="content",s){if(!e||e.length===0)return;if(s?.useIndividualBullets){o1e({slide:r,bullets:e,startX:t.x,startY:t.y,width:t.w,theme:n,itemSpacing:s.itemSpacing??.45});return}let i=Vee(o),a=ete(e.length,i.baseFontSize||n.fonts.sizes.body),l=[];e.forEach(u=>{if(!u||!u.text)return;let d=u.bulletStyle||i.bulletStyle||"disc",p=u.fontSize||a,m=u.color?.replace("#","")||n.colors.text.replace("#",""),f=u.bold??u.emphasis??!1,h;if(u.icon?h={code:u.icon}:h=Gee(d),Dv(u.text)){let y=Nv(u.text),v=Lv(y,{fontSize:p,fontFace:n.fonts.body,color:m,baseBold:f});l.push({text:v,options:{bullet:h,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}})}else l.push({text:u.text,options:{bullet:h,fontSize:p,fontFace:n.fonts.body,color:m,bold:f,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}});u.subBullets&&u.subBullets.length>0&&u.subBullets.forEach(y=>{if(Dv(y)){let v=Nv(y),b=Lv(v,{fontSize:Math.max(10,p-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#","")});l.push({text:b,options:{bullet:!0,indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})}else l.push({text:y,options:{bullet:!0,fontSize:Math.max(10,p-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})})}),r.addText(l,{x:t.x,y:t.y,w:t.w,h:t.h,valign:"top",fit:kt})}function tte(r,e,t){let n=WB(e);if(!n.isValid&&n.format===""){g.warn("[addImage] Invalid image buffer",{error:n.error});return}n.isValid||g.warn("[addImage] Image validation warning, attempting to add anyway",{error:n.error,mimeType:n.mimeType});let o=Ow(e);if(!o){g.warn("[addImage] Failed to convert buffer to data URL");return}try{r.addImage({data:o,x:t.x,y:t.y,w:t.w,h:t.h,sizing:{type:"cover",w:t.w,h:t.h}})}catch(s){g.error("[addImage] Failed to add image to slide",{error:s instanceof Error?s.message:String(s)})}}function WQt(r){switch(r){case"chart-bar":return"bar";case"chart-line":return"line";case"chart-pie":return"pie";case"chart-area":return"area";default:return"bar"}}function i1e(r,e,t,n,o){let s=t.layoutOptions||{},i=s.title||{},a=s.subtitle||{},l=s.background||{},u=o?Ow(o):null;if(u)r.background={data:u},r.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}});else if(l.color||l.useThemePrimary||l.useThemeSecondary){let f=l.useThemePrimary?n.colors.primary:l.useThemeSecondary?n.colors.secondary:l.color||n.colors.background;r.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:f.replace("#","")}})}let d=o||l.color||l.useThemePrimary||l.useThemeSecondary,p=d?"FFFFFF":n.colors.text.replace("#",""),m=d?"FFFFFF":n.colors.muted.replace("#","");r.addText(e,{x:i.x??.5,y:i.y??2,w:i.w??9,h:i.h??1.2,fontSize:i.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:i.color?.replace("#","")??p,align:i.align??"center",bold:!0,fit:kt}),t.subtitle&&r.addText(t.subtitle,{x:a.x??.5,y:a.y??3.3,w:a.w??9,h:a.h??.6,fontSize:a.fontSize??n.fonts.sizes.subtitle,fontFace:n.fonts.body,color:a.color?.replace("#","")??m,align:a.align??"center",fit:kt})}function a1e(r,e,t,n){let o=t.layoutOptions||{},s=o.sectionNumber||{},i=o.title||{},a=o.subtitle||{},l=o.background||{};if(l.color&&r.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:l.color.replace("#","")}}),t.sectionNumber){let u=s.style==="watermark",d=s.style==="small";r.addText(String(t.sectionNumber).padStart(2,"0"),{x:s.x??(u?5.5:.5),y:s.y??(u?.5:1.5),w:u?5:2,h:u?4:1,fontSize:s.fontSize??(u?200:d?32:72),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:u?"right":"left",transparency:u?70:0})}r.addText(e,{x:i.x??.5,y:i.y??2.5,w:i.w??9,h:i.h??1,fontSize:i.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),bold:!0,align:i.align??"left"}),t.subtitle&&r.addText(t.subtitle,{x:a.x??.5,y:a.y??3.6,w:a.w??8,h:a.h??.6,fontSize:a.fontSize??n.fonts.sizes.subtitle,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:a.align??"left"})}function c1e(r,e,t,n,o){if(o){let i=Ow(o);i&&(r.background={data:i},r.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}}))}let s=o?"FFFFFF":n.colors.text.replace("#","");if(r.addText(e||"Thank You!",{x:.5,y:1.8,w:9,h:1,fontSize:n.fonts.sizes.title,fontFace:n.fonts.heading,color:s,align:"center",bold:!0,fit:kt}),t.cta&&r.addText(t.cta,{x:.5,y:2.9,w:9,h:.5,fontSize:n.fonts.sizes.subtitle,fontFace:n.fonts.body,color:o?"FFFFFF":n.colors.muted.replace("#",""),align:"center",fit:kt}),t.contactInfo){let i=[];if(t.contactInfo.email&&i.push(`Email: ${t.contactInfo.email}`),t.contactInfo.website&&i.push(`Web: ${t.contactInfo.website}`),t.contactInfo.phone&&i.push(`Phone: ${t.contactInfo.phone}`),i.length>0&&r.addText(i.join(" \u2022 "),{x:.5,y:4.2,w:9,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:s,align:"center",fit:kt}),t.contactInfo.social&&Array.isArray(t.contactInfo.social)&&t.contactInfo.social.length>0){let a=t.contactInfo.social.map(l=>`${l.platform||""}: ${l.handle||""}`).join(" \u2022 ");r.addText(a,{x:.5,y:4.7,w:9,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:o?"CCCCCC":n.colors.muted.replace("#",""),align:"center"})}}}function JB(r){let{slide:e,title:t,content:n,layout:o,theme:s,imageBuffer:i,slideType:a="content"}=r;Ri(e,t,s);let l=i&&o.includes("image"),u=l?o.includes("left")?Nt.contentRight:Nt.contentLeft:Nt.contentFull;if(n.bullets&&n.bullets.length>0?s1e(e,n.bullets,u,s,a):n.body&&e.addText(n.body,{x:u.x,y:u.y,w:u.w,h:u.h,fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:s.colors.text.replace("#",""),valign:"top"}),i&&l){let d=o.includes("left")?Nt.imageLeft:Nt.imageRight;tte(e,i,d)}}function l1e(r,e,t,n,o,s){if(n==="image-full-overlay"&&s){let i=Ow(s);i?(r.background={data:i},r.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:50}}),r.addText(e,{x:.5,y:4.2,w:9,h:1,fontSize:o.fonts.sizes.heading,fontFace:o.fonts.heading,color:"FFFFFF",bold:!0,fit:kt})):Ri(r,e,o)}else n==="image-centered"||n==="image-full-overlay"?(Ri(r,e,o),s?tte(r,s,Nt.imageCentered):(r.addShape("rect",{x:1.5,y:1.8,w:7,h:3.5,fill:{color:o.colors.muted.replace("#",""),transparency:90},line:{color:o.colors.muted.replace("#",""),width:1,dashType:"dash"}}),r.addText("\u{1F4F7}",{x:1.5,y:2.8,w:7,h:1,fontSize:48,align:"center",valign:"middle",fit:kt}),r.addText("Image not available",{x:1.5,y:3.8,w:7,h:.5,fontSize:12,fontFace:o.fonts.body,color:o.colors.muted.replace("#",""),align:"center",fit:kt})),t.caption&&r.addText(t.caption,{x:.5,y:5,w:9,h:.4,fontSize:o.fonts.sizes.caption,fontFace:o.fonts.body,color:o.colors.muted.replace("#",""),align:"center",fit:kt})):JB({slide:r,title:e,content:t,layout:n,theme:o,imageBuffer:s})}function u1e(r,e,t,n,o){Ri(r,e,n,!1);let s={headerY:o?.headerY??1.3,headerHeight:o?.headerHeight??.5,bulletsStartY:o?.bulletsStartY??2,columnGap:o?.columnGap??.3,highlightFirstColumn:o?.highlightFirstColumn??!0},i=t.length;if(i===0)return;let a=9,l=(i-1)*s.columnGap,u=(a-l)/i,d=.5;t.forEach((p,m)=>{if(!p)return;let f=d+m*(u+s.columnGap),h=s.highlightFirstColumn&&m===0;if(p.title){r.addShape("roundRect",{x:f,y:s.headerY,w:u,h:s.headerHeight,fill:{color:h?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05});let y=i<=2?n.fonts.sizes.body:n.fonts.sizes.body-2;r.addText(p.title,{x:f,y:s.headerY,w:u,h:s.headerHeight,fontSize:y,fontFace:n.fonts.heading,color:h?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:kt})}p.bullets&&p.bullets.length>0&&o1e({slide:r,bullets:p.bullets,startX:f,startY:s.bulletsStartY,width:u,theme:n})})}function d1e(r,e,t,n,o,s){let i=[];t.leftColumn&&i.push(t.leftColumn),t.rightColumn&&i.push(t.rightColumn),i.length>0&&u1e(r,e,i,o,{highlightFirstColumn:!0}),s&&!t.rightColumn?.bullets&&tte(r,s,Nt.columnRight)}function p1e(r,e,t,n){let o=[];t.leftColumn&&o.push(t.leftColumn),t.centerColumn&&o.push(t.centerColumn),t.rightColumn&&o.push(t.rightColumn),o.length>0&&u1e(r,e,o,n,{highlightFirstColumn:!0})}function m1e(r,e,t,n){if(r.addText("\u201C",{x:.5,y:1,w:1,h:1,fontSize:120,fontFace:"Georgia",color:n.colors.primary.replace("#",""),fit:kt}),t.quote&&r.addText(t.quote,{x:Nt.quote.x,y:Nt.quote.y,w:Nt.quote.w,h:Nt.quote.h,fontSize:n.fonts.sizes.heading,fontFace:"Georgia",color:n.colors.text.replace("#",""),italic:!0,valign:"middle",fit:kt}),t.quoteAuthor){let o=`\u2014 ${t.quoteAuthor}`;t.quoteAuthorTitle&&(o+=`, ${t.quoteAuthorTitle}`),r.addText(o,{x:Nt.quoteAuthor.x,y:Nt.quoteAuthor.y,w:Nt.quoteAuthor.w,h:Nt.quoteAuthor.h,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"right",fit:kt})}}function f1e(r,e,t,n){if(Ri(r,e,n),!t.statistics||t.statistics.length===0)return;let o=t.statistics.slice(0,4),s=9/o.length;o.forEach((i,a)=>{let l=.5+a*s;if(r.addText(i.value,{x:l,y:Nt.statRow.y,w:s-.2,h:1.2,fontSize:48,fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",fit:kt}),r.addText(i.label,{x:l,y:Nt.statRow.y+1.3,w:s-.2,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),align:"center",fit:kt}),i.change||i.trend){let u=i.trend==="up"?"22C55E":i.trend==="down"?"EF4444":n.colors.muted.replace("#",""),d=i.trend==="up"?"(+)":i.trend==="down"?"(-)":"";r.addText(`${d} ${i.change||""}`,{x:l,y:Nt.statRow.y+1.8,w:s-.2,h:.4,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:u,align:"center",fit:kt})}})}function g1e(r,e,t,n,o){if(Ri(r,e,o),!t.chartData||!t.chartData.series||t.chartData.series.length===0){r.addText("No chart data available",{x:Nt.chart.x,y:Nt.chart.y+1,w:Nt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:kt});return}let s=t.chartData.series.filter(l=>l.name&&Array.isArray(l.labels)&&l.labels.length>0&&Array.isArray(l.values)&&l.values.length>0);if(s.length===0){r.addText("Invalid chart data format",{x:Nt.chart.x,y:Nt.chart.y+1,w:Nt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:kt});return}let i=WQt(n),a=s.map(l=>({name:l.name,labels:l.labels,values:l.values}));r.addChart(i,a,{x:Nt.chart.x,y:Nt.chart.y,w:Nt.chart.w,h:Nt.chart.h,showTitle:!!t.chartData.title,title:t.chartData.title,showLegend:t.chartData.legendPosition!=="none",legendPos:GQt[t.chartData.legendPosition||"bottom"]||"b",showValue:t.chartData.showLabels,chartColors:[o.colors.primary.replace("#",""),o.colors.secondary.replace("#",""),o.colors.accent.replace("#","")]})}function h1e(r,e,t,n){if(Ri(r,e,n),!t.tableData)return;let{headers:o,rows:s,hasHeader:i}=t.tableData,a=[];i&&o&&a.push(o.map(l=>({text:l,options:{bold:!0,fill:{color:n.colors.primary.replace("#","")},color:n.colors.textOnPrimary.replace("#",""),align:"center"}}))),s.forEach((l,u)=>{a.push(l.map(d=>({text:d.text,options:{fill:{color:u%2===0?"F8FAFC":"FFFFFF"},color:n.colors.text.replace("#",""),align:d.align||"left"}})))}),r.addTable(a,{x:Nt.chart.x,y:Nt.chart.y,w:Nt.chart.w,colW:Array(o?.length||s[0]?.length||1).fill(Nt.chart.w/(o?.length||s[0]?.length||1)),fontSize:n.fonts.sizes.body-2,fontFace:n.fonts.body,border:{pt:.5,color:"E2E8F0"},autoPage:!0}),t.tableData.caption&&r.addText(t.tableData.caption,{x:.5,y:5.1,w:9,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center"})}function y1e(r,e,t,n){if(Ri(r,e,n),!t.timeline?.items)return;let o=t.timeline.items.slice(0,5);t.timeline.orientation!=="vertical"?KQt(r,o,n):JQt(r,o,n)}function KQt(r,e,t){let n=8/e.length,o=2.8;r.addShape("rect",{x:1,y:o,w:8,h:.02,fill:{color:t.colors.primary.replace("#","")}}),e.forEach((s,i)=>{let a=1+i*n+n/2-.15;r.addShape("ellipse",{x:a,y:o-.15,w:.3,h:.3,fill:{color:t.colors.primary.replace("#","")}}),r.addText(s.date,{x:a-n/2+.15,y:o-.8,w:n,h:.4,fontSize:t.fonts.sizes.caption,fontFace:t.fonts.body,color:t.colors.primary.replace("#",""),align:"center",bold:!0,fit:kt}),r.addText(s.title,{x:a-n/2+.15,y:o+.4,w:n,h:.4,fontSize:t.fonts.sizes.body,fontFace:t.fonts.heading,color:t.colors.text.replace("#",""),align:"center",bold:!0,fit:kt}),s.description&&r.addText(s.description,{x:a-n/2+.15,y:o+.85,w:n,h:.8,fontSize:t.fonts.sizes.caption,fontFace:t.fonts.body,color:t.colors.muted.replace("#",""),align:"center",fit:kt})})}function JQt(r,e,t){let n=3/e.length,o=1.5;r.addShape("rect",{x:o,y:1.5,w:.04,h:3.5,fill:{color:t.colors.primary.replace("#","")}}),e.forEach((s,i)=>{let a=1.7+i*n;r.addShape("ellipse",{x:o-.12,y:a,w:.28,h:.28,fill:{color:t.colors.primary.replace("#","")}}),r.addText(s.date,{x:.3,y:a-.1,w:1,h:.3,fontSize:t.fonts.sizes.caption,fontFace:t.fonts.body,color:t.colors.primary.replace("#",""),bold:!0,fit:kt}),r.addText(s.title,{x:2,y:a-.1,w:7,h:.4,fontSize:t.fonts.sizes.body,fontFace:t.fonts.heading,color:t.colors.text.replace("#",""),bold:!0,fit:kt}),s.description&&r.addText(s.description,{x:2,y:a+.3,w:7,h:.4,fontSize:t.fonts.sizes.caption,fontFace:t.fonts.body,color:t.colors.muted.replace("#",""),fit:kt})})}function v1e(r,e,t,n){if(Ri(r,e,n),!t.processSteps)return;let o=t.processSteps.slice(0,5),s=8/o.length;o.forEach((i,a)=>{let l=1+a*s,u=s-.4;r.addShape("roundRect",{x:l,y:2,w:u,h:2,fill:{color:n.colors.primary.replace("#","")},rectRadius:.1}),r.addText(String(i.step),{x:l,y:2.1,w:u,h:.5,fontSize:24,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:kt}),r.addText(i.title,{x:l,y:2.6,w:u,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:kt}),i.description&&r.addText(i.description,{x:l,y:3.2,w:u,h:.7,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.textOnPrimary.replace("#",""),align:"center",fit:kt}),a<o.length-1&&r.addShape("rightArrow",{x:l+u+.02,y:2.85,w:.35,h:.3,fill:{color:n.colors.primary.replace("#","")}})})}function x1e(r,e,t,n){if(Ri(r,e,n,!1),!t.comparison?.columns)return;let o=t.comparison.columns.slice(0,2),s=4.2,i=2,l=5-i,u=Math.max(...o.map(m=>Math.min(m.items?.length||0,6))),d=u>0?Math.min(.7,(l-jA*u)/u):.5,p=d+jA;o.forEach((m,f)=>{let h=.5+f*4.8;r.addShape("roundRect",{x:h,y:1.4,w:s,h:.5,fill:{color:m.highlight?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05}),r.addText(m.title,{x:h,y:1.4,w:s,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:m.highlight?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:kt});let y=(m.items||[]).slice(0,6),v=y.length>4?Math.max(12,n.fonts.sizes.body-2):n.fonts.sizes.body;y.forEach((b,S)=>{if(Dv(b)){let w=Nv(b),_=[{text:"\u2022 ",options:{fontSize:v,fontFace:n.fonts.body,color:n.colors.text.replace("#","")}},...Lv(w,{fontSize:v,fontFace:n.fonts.body,color:n.colors.text.replace("#","")})];r.addText(_,{x:h+.2,y:i+S*p,w:s-.4,h:d,valign:"top",fit:kt})}else r.addText(`\u2022 ${b}`,{x:h+.2,y:i+S*p,w:s-.4,h:d,fontSize:v,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top",fit:kt})})})}function b1e(r,e,t,n){Ri(r,e,n);let o=t.features||[],s=t.icons||[],i=o.length>0?o:s.map(u=>({title:u.label,description:u.description||"",icon:u.icon}));if(i.length===0)return;let a=Math.min(i.length,3),l=9/a;i.slice(0,6).forEach((u,d)=>{let p=Math.floor(d/a),f=.5+d%a*l,h=1.6+p*1.8;if(u.icon){let y=parseInt(u.icon,16);if(!Number.isNaN(y)&&y>=0&&y<=1114111){let v=String.fromCodePoint(y);r.addText(v,{x:f,y:h,w:l-.2,h:.6,fontSize:36,fontFace:"Segoe UI Emoji",color:n.colors.primary.replace("#",""),align:"center",fit:kt})}}r.addText(u.title,{x:f,y:h+.6,w:l-.2,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),align:"center",bold:!0,fit:kt}),u.description&&r.addText(u.description,{x:f,y:h+1,w:l-.2,h:.6,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:kt})})}function T1e(r,e,t,n){if(Ri(r,e,n),!t.teamMembers)return;let o=t.teamMembers.slice(0,4),s=9/o.length;o.forEach((i,a)=>{let l=.5+a*s;r.addShape("ellipse",{x:l+(s-1.5)/2,y:1.6,w:1.5,h:1.5,fill:{color:n.colors.muted.replace("#","")}});let u=i.name.split(" ").map(d=>d[0]).join("").substring(0,2);r.addText(u,{x:l+(s-1.5)/2,y:2,w:1.5,h:.7,fontSize:28,fontFace:n.fonts.heading,color:"FFFFFF",align:"center",bold:!0,fit:kt}),r.addText(i.name,{x:l,y:3.3,w:s-.2,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),align:"center",bold:!0,fit:kt}),r.addText(i.role,{x:l,y:3.7,w:s-.2,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:kt})})}function S1e(r,e,t,n){if(Ri(r,e,n),t.bullets){let o=t.bullets.map(s=>({...s,icon:s.icon||"2713"}));s1e(r,o,Nt.contentFull,n,"conclusion")}t.cta&&r.addText(t.cta,{x:.5,y:4.6,w:9,h:.5,fontSize:n.fonts.sizes.heading-4,fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),align:"center",bold:!0,fit:kt})}function Nw(r,e,t,n,o=!1){r.addShape("roundRect",{x:e.x,y:e.y,w:e.w,h:e.h,fill:{color:o?n.colors.primary.replace("#","")+"15":"F8F9FA"},line:{color:o?n.colors.primary.replace("#",""):"E5E7EB",width:1},rectRadius:.1});let s=e.y+.15,i=e.h-.3;return t&&(r.addText(t,{x:e.x+.15,y:e.y+.1,w:e.w-.3,h:.35,fontSize:14,fontFace:n.fonts.heading,color:o?n.colors.primary.replace("#",""):n.colors.text.replace("#",""),bold:!0,fit:kt}),s=e.y+.45,i=e.h-.55),{contentY:s,contentH:i}}function w1e(r,e,t,n,o,s){if(!e||e.length===0)return;let i=Math.max(11,Math.min(14,16-e.length)),a=n.colors.text.replace("#","");e.forEach((l,u)=>{if(!l||!l.text)return;let d=o+u*(s/e.length);if(Dv(l.text)){let p=Nv(l.text),m=[{text:"\u2022 ",options:{fontSize:i,fontFace:n.fonts.body,color:a}},...Lv(p,{fontSize:i,fontFace:n.fonts.body,color:a})];r.addText(m,{x:t.x+.15,y:d,w:t.w-.3,h:s/e.length,valign:"top",fit:kt})}else r.addText(`\u2022 ${l.text}`,{x:t.x+.15,y:d,w:t.w-.3,h:s/e.length,fontSize:i,fontFace:n.fonts.body,color:a,valign:"top",fit:kt})})}function rte(r,e,t,n,o,s){r.addText(e.value,{x:t.x,y:o,w:t.w,h:s*.6,fontSize:Math.min(32,t.w*8),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",valign:"bottom",fit:kt}),r.addText(e.label,{x:t.x,y:o+s*.6,w:t.w,h:s*.4,fontSize:11,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",valign:"top",fit:kt})}function _1e(r){let{slide:e,icon:t,label:n,description:o,pos:s,theme:i,contentY:a,contentH:l}=r,u=Math.min(.6,s.w*.2);e.addShape("ellipse",{x:s.x+(s.w-u)/2,y:a,w:u,h:u,fill:{color:i.colors.primary.replace("#","")}});let d=parseInt(t,16);if(Number.isNaN(d)||d<0||d>1114111){g.warn("[renderIconBoxInZone] Invalid icon code",{icon:t});return}let p=String.fromCodePoint(d);e.addText(p,{x:s.x+(s.w-u)/2,y:a,w:u,h:u,fontSize:16,color:"FFFFFF",align:"center",valign:"middle",fit:kt}),e.addText(n,{x:s.x,y:a+u+.1,w:s.w,h:.3,fontSize:12,fontFace:i.fonts.heading,color:i.colors.text.replace("#",""),bold:!0,align:"center",fit:kt}),o&&e.addText(o,{x:s.x+.1,y:a+u+.4,w:s.w-.2,h:l-u-.5,fontSize:10,fontFace:i.fonts.body,color:i.colors.muted.replace("#",""),align:"center",fit:kt})}function E1e(r,e,t,n,o,s){let i=e.type==="pie"?"pie":e.type==="line"?"line":"bar",a=e.series||[];if(a.length===0)return;let l=a.map(u=>({name:u.name||"Data",labels:u.labels||[],values:u.values||[]}));try{r.addChart(i,l,{x:t.x+.1,y:o,w:t.w-.2,h:s,showLegend:!1,showTitle:!1,chartColors:[n.colors.primary.replace("#",""),n.colors.secondary.replace("#",""),n.colors.accent.replace("#",""),n.colors.muted.replace("#","")]})}catch{r.addText("Chart",{x:t.x,y:o,w:t.w,h:s,fontSize:14,color:n.colors.muted.replace("#",""),align:"center",valign:"middle",fit:kt})}}function C1e(r,e,t,n){Ri(r,e,n,!1);let o=Da[t.layout]||Da["left-right"];(t.zones||[]).forEach((i,a)=>{if(a>=o.length)return;let l=o[a],{contentY:u,contentH:d}=Nw(r,l,i.title,n,i.isPrimary);switch(i.type){case"bullets":Array.isArray(i.data)&&w1e(r,i.data,l,n,u,d);break;case"stats":i.data&&typeof i.data=="object"&&rte(r,i.data,l,n,u,d);break;case"icon-box":if(i.data&&typeof i.data=="object"){let p=i.data;_1e({slide:r,icon:p.icon,label:p.label,description:p.description,pos:l,theme:n,contentY:u,contentH:d})}break;case"chart":i.data&&typeof i.data=="object"&&E1e(r,i.data,l,n,u,d);break;case"text-box":typeof i.data=="string"&&r.addText(i.data,{x:l.x+.15,y:u,w:l.w-.3,h:d,fontSize:12,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top"});break}})}function k1e(r,e,t,n){if(Ri(r,e,n,!1),t.bullets&&t.bullets.length>0){let o=Da["left-right"][0],{contentY:s,contentH:i}=Nw(r,o,t.leftColumn?.title,n,!0);w1e(r,t.bullets,o,n,s,i)}if(t.chartData){let o=Da["left-right"][1],{contentY:s,contentH:i}=Nw(r,o,"Data",n,!1);E1e(r,t.chartData,o,n,s,i)}else if(t.statistics&&t.statistics.length>0){let o=Da["left-right"][1];Nw(r,o,"Metrics",n,!1);let s=t.statistics.slice(0,3),i=o.h/s.length;s.forEach((a,l)=>{rte(r,a,{...o,y:o.y+l*i,h:i},n,o.y+l*i+.1,i-.2)})}}function R1e(r,e,t,n){Ri(r,e,n,!1);let o=t.statistics||[];if(o.length===0)return;let s;o.length<=2?s=Da["left-right"]:o.length<=3?s=Da["three-cols"]:o.length<=4?s=Da.quadrants:o.length<=5?s=Da["five-boxes"]:s=Da["six-boxes"],o.slice(0,s.length).forEach((i,a)=>{let l=s[a],u=a===0,{contentY:d,contentH:p}=Nw(r,l,void 0,n,u);rte(r,i,l,n,d,p)})}function A1e(r,e,t,n){Ri(r,e,n,!1);let o=t.icons||t.features||[];if(o.length===0)return;let s;o.length<=2?s=Da["left-right"]:o.length<=3?s=Da["three-cols"]:o.length<=4?s=Da.quadrants:o.length<=5?s=Da["five-boxes"]:s=Da["six-boxes"],o.slice(0,s.length).forEach((i,a)=>{let l=s[a],u=a===0,{contentY:d,contentH:p}=Nw(r,l,void 0,n,u),m=i.icon||"1F4A1",f=i.title||i.label||"",h=i.description;_1e({slide:r,icon:m,label:f,description:h,pos:l,theme:n,contentY:d,contentH:p})})}var jA,kt,Nt,GQt,Da,I1e=A(()=>{"use strict";Q();Ov();KB();jA=.1,kt="shrink",Nt={margin:{x:.5,y:.4},title:{x:.5,y:.4,w:9,h:.8},subtitle:{x:.5,y:1.4,w:9,h:.5},content:{x:.5,y:1.4,w:9,h:3.8},contentFull:{x:.5,y:1.4,w:9,h:3.8},contentLeft:{x:.5,y:1.4,w:4.2,h:3.8},contentRight:{x:5.3,y:1.4,w:4.2,h:3.8},imageRight:{x:5.3,y:1.4,w:4.2,h:3.8},imageLeft:{x:.5,y:1.4,w:4.2,h:3.8},imageFull:{x:0,y:0,w:10,h:5.625},imageCentered:{x:2,y:1.2,w:6,h:3.6},columnLeft:{x:.5,y:1.4,w:4.2,h:3.8},columnRight:{x:5.3,y:1.4,w:4.2,h:3.8},col1:{x:.5,y:1.4,w:2.8,h:3.8},col2:{x:3.5,y:1.4,w:2.8,h:3.8},col3:{x:6.5,y:1.4,w:2.8,h:3.8},chart:{x:.5,y:1.4,w:9,h:3.8},statRow:{y:2.2,h:2.5},footer:{x:.5,y:5.2,w:9,h:.3},logo:{"top-left":{x:.3,y:.2},"top-right":{x:8.5,y:.2},"bottom-left":{x:.3,y:5},"bottom-right":{x:8.5,y:5}},quote:{x:1,y:1.5,w:8,h:2.5},quoteAuthor:{x:1,y:4.2,w:8,h:.5}},GQt={top:"t",bottom:"b",left:"l",right:"r"};Da={"left-right":[{x:.5,y:1.4,w:4.3,h:3.6},{x:5.2,y:1.4,w:4.3,h:3.6}],"top-bottom":[{x:.5,y:1.2,w:9,h:1.8},{x:.5,y:3.2,w:9,h:2}],"three-cols":[{x:.5,y:1.4,w:2.8,h:3.6},{x:3.5,y:1.4,w:2.8,h:3.6},{x:6.5,y:1.4,w:2.8,h:3.6}],quadrants:[{x:.5,y:1.2,w:4.3,h:1.8},{x:5.2,y:1.2,w:4.3,h:1.8},{x:.5,y:3.2,w:4.3,h:1.8},{x:5.2,y:3.2,w:4.3,h:1.8}],"five-boxes":[{x:.5,y:1.2,w:4.3,h:1.6},{x:5.2,y:1.2,w:4.3,h:1.6},{x:.5,y:3,w:2.8,h:2},{x:3.5,y:3,w:2.8,h:2},{x:6.5,y:3,w:2.8,h:2}],"six-boxes":[{x:.5,y:1.2,w:2.8,h:1.6},{x:3.5,y:1.2,w:2.8,h:1.6},{x:6.5,y:1.2,w:2.8,h:1.6},{x:.5,y:3,w:2.8,h:1.8},{x:3.5,y:3,w:2.8,h:1.8},{x:6.5,y:3,w:2.8,h:1.8}],"main-sidebar":[{x:.5,y:1.4,w:5.8,h:3.6},{x:6.5,y:1.4,w:3,h:3.6}],"top-three":[{x:.5,y:1.2,w:9,h:1.6},{x:.5,y:3,w:2.8,h:2},{x:3.5,y:3,w:2.8,h:2},{x:6.5,y:3,w:2.8,h:2}]}});var P1e={};le(P1e,{Agent:()=>Ler,BedrockClient:()=>XQt,BedrockRuntimeClient:()=>QQt,Blob:()=>Der,Client:()=>Uer,ConverseCommand:()=>eer,ConverseStreamCommand:()=>ter,Cron:()=>yer,Dispatcher:()=>$er,File:()=>Ner,FlowProducer:()=>her,FormData:()=>Oer,GoogleAuth:()=>ier,HTTPException:()=>_er,Headers:()=>Mer,Hippocampus:()=>ler,HippocampusConfig:()=>uer,Hono:()=>Ser,ImageFormat:()=>rer,InvokeEndpointCommand:()=>oer,InvokeEndpointWithResponseStreamCommand:()=>ser,Job:()=>fer,ListFoundationModelsCommand:()=>YQt,MockAgent:()=>jer,Pool:()=>Fer,Queue:()=>per,QueueScheduler:()=>ger,Request:()=>Ier,Response:()=>Per,SageMakerRuntimeClient:()=>ner,TextToSpeechClient:()=>cer,VertexAI:()=>aer,Worker:()=>mer,convertToHtml:()=>Ter,cors:()=>wer,createClient:()=>der,default:()=>ZQt,extractRawText:()=>ber,fetch:()=>Aer,getGlobalDispatcher:()=>Ber,interceptors:()=>qer,logger:()=>Eer,parseBuffer:()=>ver,request:()=>Ver,secureHeaders:()=>Cer,selectCover:()=>xer,setGlobalDispatcher:()=>zer,streamSSE:()=>ker,timeout:()=>Rer});var Dw,Hs,ZQt,XQt,YQt,QQt,eer,ter,rer,ner,oer,ser,ier,aer,cer,ler,uer,der,per,mer,fer,ger,her,yer,ver,xer,ber,Ter,Ser,wer,_er,Eer,Cer,ker,Rer,Aer,Ier,Per,Mer,Oer,Ner,Der,Ler,Fer,Uer,$er,zer,Ber,jer,qer,Ver,M1e=A(()=>{Dw={get(r,e){return e==="__esModule"?!0:e==="default"?new Proxy({},{get:Dw.get}):new Proxy(function(...t){return new Proxy({},{get:Dw.get})},{get:Dw.get,apply(t,n,o){return new Proxy({},{get:Dw.get})},construct(t,n){return new Proxy({},{get:Dw.get})}})}},Hs=new Proxy({},Dw),ZQt=Hs,{BedrockClient:XQt,ListFoundationModelsCommand:YQt,BedrockRuntimeClient:QQt,ConverseCommand:eer,ConverseStreamCommand:ter,ImageFormat:rer}=Hs,{SageMakerRuntimeClient:ner,InvokeEndpointCommand:oer,InvokeEndpointWithResponseStreamCommand:ser}=Hs,{GoogleAuth:ier,VertexAI:aer,TextToSpeechClient:cer}=Hs,{Hippocampus:ler,HippocampusConfig:uer}=Hs,{createClient:der}=Hs,{Queue:per,Worker:mer,Job:fer,QueueScheduler:ger,FlowProducer:her}=Hs,{Cron:yer}=Hs,{parseBuffer:ver,selectCover:xer}=Hs,{extractRawText:ber,convertToHtml:Ter}=Hs,{Hono:Ser}=Hs,{cors:wer,HTTPException:_er,logger:Eer,secureHeaders:Cer,streamSSE:ker,timeout:Rer}=Hs,Aer=globalThis.fetch,Ier=globalThis.Request,Per=globalThis.Response,Mer=globalThis.Headers,Oer=globalThis.FormData,Ner=globalThis.File,Der=globalThis.Blob,Ler=Hs.Agent,Fer=Hs.Pool,Uer=Hs.Client,$er=Hs.Dispatcher,zer=()=>{},Ber=()=>Hs,jer=Hs.MockAgent,qer={redirect:()=>r=>r,retry:()=>r=>r},Ver=async(r,e)=>{let t=await globalThis.fetch(r,e);return{statusCode:t.status,headers:Object.fromEntries(t.headers.entries()),body:{text:()=>t.text(),json:()=>t.json(),arrayBuffer:()=>t.arrayBuffer()}}}});async function O1e(){if(ZB)return ZB;try{let r=await Promise.resolve().then(()=>(M1e(),P1e));return ZB=typeof r.default=="function"?r.default:r.default.default,ZB}catch(r){let e=r instanceof Error?r:null;throw e?.code==="ERR_MODULE_NOT_FOUND"&&e.message.includes("pptxgenjs")?new Error(`PPT generation requires the "pptxgenjs" package. Install it with:
|
|
2167
|
-
pnpm add pptxgenjs`,{cause:r}):r}}var ZB,XB,nte=A(async()=>{"use strict";aR();dn();vr();Ov();Q();bt();bo();I1e();ZB=null;XB=class{theme;config;neurolink;imageLimit;userImageIndex=0;constructor(e){this.config=e,this.theme=typeof e.theme=="string"?zee(e.theme):e.theme,this.neurolink=e.neurolink||null,this.imageLimit=op(Wee)}getNextUserImage(){let e=this.config.userImages;if(!e||e.length===0)return;let t=e[this.userImageIndex%e.length];return this.userImageIndex++,t}async loadUserImage(e){try{if(Buffer.isBuffer(e))return e;if(e.startsWith("http://")||e.startsWith("https://")){let o=await Oe(fetch(e),15e3,pe.toolTimeout("userImageFetch",15e3));if(!o.ok){g.warn(`[SlideGenerator] Failed to fetch user image: ${e}`);return}return Buffer.from(await o.arrayBuffer())}return await(await Promise.resolve().then(()=>(Pu(),$f))).readFile(e)}catch(n){g.warn("[SlideGenerator] Failed to load user image",{error:n instanceof Error?n.message:String(n)});return}}async generateSlide(e){let t=xe.createSpan("ppt.generation","ppt.generateSlide",{"ppt.operation":"generateSlide","ppt.slideIndex":e.slideNumber,"ppt.theme":this.theme.name}),n=Date.now();try{let o,s;if(zA(e.type)){let l=this.getNextUserImage();if(l&&(g.info(`[SlideGenerator] \u{1F4F7} Using user-provided image for slide ${e.slideNumber}: "${e.title}"`),o=await this.loadUserImage(l),o&&(s={prompt:"User-provided image",model:"user-upload",generatedAt:new Date})),!o&&this.config.generateAIImages&&e.imagePrompt){g.info(`[SlideGenerator] \u23F3 Generating AI image for slide ${e.slideNumber}: "${e.title}"...`);let u=await this.generateImage(e.imagePrompt,e.type);u&&(o=u.buffer,s={prompt:e.imagePrompt,model:u.model,generatedAt:new Date})}}let i=Date.now()-n;g.debug(`[SlideGenerator] Generated slide ${e.slideNumber} (${e.type})`,{hasImage:!!o,generationTime:i});let a=xe.endSpan(t,1);return Ue().recordSpan(a),{slideNumber:e.slideNumber,schema:e,imageBuffer:o,imageMetadata:s,generationTime:i}}catch(o){let s=xe.endSpan(t,2);s.statusMessage=o instanceof Error?o.message:String(o),Ue().recordSpan(s);let i=o instanceof Je?o:pe.toolExecutionFailed("slideGenerator",o instanceof Error?o:new Error(String(o)));return g.error(`[SlideGenerator] Failed to generate slide ${e.slideNumber}`,{error:i.message,type:e.type}),{slideNumber:e.slideNumber,schema:e,generationTime:Date.now()-n}}}async generateSlides(e){let t=Date.now(),n=this.config.generateAIImages?e.filter(d=>d.imagePrompt&&zA(d.type)).length:0,o=this.config.userImages?.length??0;g.info(`[SlideGenerator] Generating ${e.length} slides...`,{theme:this.theme.name,generateAIImages:this.config.generateAIImages,slidesNeedingAIImages:n,userImagesProvided:o}),this.userImageIndex=0;let s=e.map(d=>this.imageLimit(()=>this.generateSlide(d))),i=await Promise.all(s),a=i.filter(d=>d.imageBuffer).length,l=this.config.generateAIImages?e.filter(d=>d.imagePrompt&&zA(d.type)&&!i.find(p=>p.slideNumber===d.slideNumber)?.imageBuffer).length:0,u=Date.now()-t;return g.info("[SlideGenerator] Slide generation complete",{totalSlides:i.length,totalImages:a,failedImages:l,generationTime:u}),{slides:i,totalImages:a,failedImages:l,generationTime:u}}renderSlide(e,t,n,o){let{schema:s,imageBuffer:i}=t,a=e.addSlide();return this.applyBackground(a,s.type),this.applyLayout(a,s,i),s.type!=="title"&&s.type!=="thank-you"&&this.addSlideNumber(a,n,o),this.addLogo(a,s.type),s.speakerNotes&&a.addNotes(s.speakerNotes),a}async generateImage(e,t){if(!this.neurolink)return g.warn("[SlideGenerator] No NeuroLink instance provided, skipping image generation"),null;try{let n=qee(e,this.theme.name);g.debug(`[SlideGenerator] Generating image for ${t}`,{promptPreview:n.substring(0,100)});let o=await Oe(this.neurolink.generate({input:{text:n},provider:this.config.provider||"vertex",model:this.config.imageModel||"gemini-2.5-flash-image"}),VB,pe.toolTimeout("imageGeneration",VB));if(!o||!o.imageOutput?.base64)return g.warn(`[SlideGenerator] No image data returned for ${t}`),null;let s=Buffer.from(o.imageOutput.base64,"base64");return s.length<100?(g.warn(`[SlideGenerator] Image buffer too small (${s.length} bytes) for ${t}`),null):(s[0]===255&&s[1]===216&&s[2]===255||s[0]===137&&s[1]===80&&s[2]===78&&s[3]===71||s[0]===71&&s[1]===73&&s[2]===70||s[0]===82&&s[1]===73&&s[2]===70&&s[3]===70||g.warn(`[SlideGenerator] Unknown image format for ${t}, magic bytes: ${s.slice(0,4).toString("hex")}`),g.debug(`[SlideGenerator] Image generated successfully for ${t}`,{size:s.length,format:s[0]===255?"JPEG":s[0]===137?"PNG":s[0]===71?"GIF":"unknown"}),{buffer:s,model:o.model||this.config.imageModel})}catch(n){let o=n instanceof Je?n:pe.toolExecutionFailed("imageGeneration",n instanceof Error?n:new Error(String(n)));return g.error("[SlideGenerator] Image generation failed",{error:o.message,slideType:t}),null}}applyBackground(e,t){e.background={color:this.theme.colors.background.replace("#","")}}applyLayout(e,t,n){let{type:o,layout:s,title:i,content:a}=t;switch(o){case"title":i1e(e,i,a,this.theme,n);break;case"section-header":a1e(e,i,a,this.theme);break;case"content":case"bullets":case"agenda":case"numbered-list":JB({slide:e,title:i,content:a,layout:s,theme:this.theme,imageBuffer:n,slideType:o});break;case"image-focus":case"image-left":case"image-right":case"full-bleed-image":l1e(e,i,a,s,this.theme,n);break;case"two-column":case"split-content":d1e(e,i,a,s,this.theme,n);break;case"three-column":p1e(e,i,a,this.theme);break;case"quote":m1e(e,i,a,this.theme);break;case"statistics":f1e(e,i,a,this.theme);break;case"chart-bar":case"chart-line":case"chart-pie":case"chart-area":g1e(e,i,a,o,this.theme);break;case"table":h1e(e,i,a,this.theme);break;case"timeline":y1e(e,i,a,this.theme);break;case"process-flow":v1e(e,i,a,this.theme);break;case"comparison":x1e(e,i,a,this.theme);break;case"features":case"icons":b1e(e,i,a,this.theme);break;case"team":T1e(e,i,a,this.theme);break;case"conclusion":S1e(e,i,a,this.theme);break;case"thank-you":case"closing":c1e(e,i,a,this.theme,n);break;case"dashboard":a.dashboard&&C1e(e,i,a.dashboard,this.theme);break;case"mixed-content":k1e(e,i,a,this.theme);break;case"stats-grid":R1e(e,i,a,this.theme);break;case"icon-grid":A1e(e,i,a,this.theme);break;case"blank":break;default:JB({slide:e,title:i,content:a,layout:s,theme:this.theme,imageBuffer:n,slideType:o})}}getLogoConfig(){return this.config.logo?Buffer.isBuffer(this.config.logo)||typeof this.config.logo=="string"?{data:this.config.logo,position:"bottom-right",width:1,height:.4,showOn:"all-slides"}:{data:this.config.logo.data,position:this.config.logo.position||"bottom-right",width:this.config.logo.width||1,height:this.config.logo.height||.4,showOn:this.config.logo.showOn||"all-slides"}:null}getLogoDataUri(e){if(Buffer.isBuffer(e))return`data:image/png;base64,${e.toString("base64")}`;if(e.startsWith("data:"))return e;if(e.includes("/")||e.includes("\\")||e.endsWith(".png")||e.endsWith(".jpg")||e.endsWith(".jpeg")||e.endsWith(".svg"))try{if(un(e)){let t=Ga(e),n=e.split(".").pop()?.toLowerCase();return`data:${n==="svg"?"image/svg+xml":n==="jpg"||n==="jpeg"?"image/jpeg":"image/png"};base64,${t.toString("base64")}`}}catch{g.warn("[SlideGenerator] Could not read logo file, treating as base64")}return`data:image/png;base64,${e}`}addLogo(e,t){let n=this.getLogoConfig();if(!n)return;let o=n.showOn||"all-slides";if(o==="title-only"&&t!=="title"||o==="title-and-closing"&&t!=="title"&&t!=="thank-you"&&t!=="closing")return;let s=this.getLogoDataUri(n.data),i=n.position||"bottom-right",a=n.width||1,l=n.height||.4,u,d,p=Nt.logo;if(i==="title-only"?(u=p["bottom-right"].x,d=p["bottom-right"].y):(u=p[i].x,d=p[i].y),i==="top-right"||i==="bottom-right"){let{width:m}=IW[this.config.aspectRatio];u=m-a-.3}if(i==="bottom-left"||i==="bottom-right"){let{height:m}=IW[this.config.aspectRatio];d=m-l-.2}e.addImage({data:s,x:u,y:d,w:a,h:l,sizing:{type:"contain",w:a,h:l}})}addSlideNumber(e,t,n){e.addText(`${t} / ${n}`,{x:Nt.footer.x,y:Nt.footer.y,w:Nt.footer.w,h:Nt.footer.h,fontSize:this.theme.fonts.sizes.caption,fontFace:this.theme.fonts.body,color:this.theme.colors.muted.replace("#",""),align:"right"})}}});function Her(r){let e=r.trim();for(let{patterns:t,slideType:n,bulletStyle:o}of Ger)for(let s of t)if(s.test(e))return{slideType:n,bulletStyle:o};return{slideType:null,bulletStyle:null}}function Ker(r){if(!r||r.length===0)return null;for(let e of r)for(let{pattern:t,bulletStyle:n}of Wer)if(t.test(e.text))return n;return null}function N1e(r){switch(r){case"agenda":case"numbered-list":return"number";case"conclusion":case"closing":case"thank-you":return"checkmark";case"comparison":return"arrow";case"features":case"icons":case"quote":case"statistics":case"title":case"section-header":return"none";default:return"disc"}}function D1e(r,e,t){let{slideType:n,bulletStyle:o}=Her(r);if(n)return{type:n,bulletStyle:o||N1e(n),wasInferred:!0};let s=t.bullets?Ker(t.bullets):null;return s?{type:e,bulletStyle:s,wasInferred:!0}:{type:e,bulletStyle:N1e(e),wasInferred:!1}}function L1e(r,e){return(r.bullets?.length??0)>0||(r.leftColumn?.bullets?.length??0)>0||(r.rightColumn?.bullets?.length??0)>0||(r.centerColumn?.bullets?.length??0)>0?{...r,bullets:r.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||e})),leftColumn:r.leftColumn?{...r.leftColumn,bullets:r.leftColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||e}))}:void 0,rightColumn:r.rightColumn?{...r.rightColumn,bullets:r.rightColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||e}))}:void 0,centerColumn:r.centerColumn?{...r.centerColumn,bullets:r.centerColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||e}))}:void 0}:r}var Ger,Wer,F1e=A(()=>{"use strict";Ger=[{patterns:[/\bagenda\b/i,/\btable\s+of\s+contents\b/i,/\boutline\b/i,/\boverview\b/i,/\bwhat\s+we('ll)?\s+cover\b/i,/\btoday('s)?\s+topics?\b/i,/\bsession\s+outline\b/i],slideType:"agenda",bulletStyle:"number"},{patterns:[/\bconclusion\b/i,/\bsummary\b/i,/\bkey\s+takeaways?\b/i,/\btakeaways?\b/i,/\brecap\b/i,/\bin\s+summary\b/i,/\bwhat\s+we('ve)?\s+learned\b/i,/\bmain\s+points?\b/i,/\bkey\s+points?\b/i,/\bhighlights?\b/i,/\bachievements?\b/i,/\baccomplishments?\b/i],slideType:"conclusion",bulletStyle:"checkmark"},{patterns:[/\bthank\s+you\b/i,/\bthanks?\b/i,/\bquestions?\b\??/i,/\bq\s*&\s*a\b/i,/\bcontact(\s+us)?\b/i,/\bnext\s+steps?\b/i,/\baction\s+items?\b/i,/\blet('s)?\s+connect\b/i,/\bget\s+(in\s+)?touch\b/i],slideType:"closing",bulletStyle:"checkmark"},{patterns:[/\bcomparison\b/i,/\bcompare\b/i,/\bvs\.?\b/i,/\bversus\b/i,/\bbefore\s+(and|&|vs\.?)\s+after\b/i,/\bpros?\s+(and|&|vs\.?)\s+cons?\b/i,/\badvantages?\s+(and|&|vs\.?)\s+disadvantages?\b/i,/\bbenefits?\s+(and|&|vs\.?)\s+risks?\b/i,/\bold\s+vs\.?\s+new\b/i],slideType:"comparison",bulletStyle:"arrow"},{patterns:[/\bprocess\b/i,/\bsteps?\b/i,/\bstep[\s-]+by[\s-]+step\b/i,/\bhow\s+to\b/i,/\bworkflow\b/i,/\bprocedure\b/i,/\bmethodology\b/i,/\d+\s+steps?\s+to\b/i,/\bimplementation\s+steps?\b/i,/\bgetting\s+started\b/i],slideType:"numbered-list",bulletStyle:"number"},{patterns:[/\bfeatures?\b/i,/\bcapabilities?\b/i,/\bwhat\s+(we|it)\s+offers?\b/i,/\bour\s+offerings?\b/i],slideType:"features",bulletStyle:"disc"},{patterns:[/\bbenefits?\b/i,/\badvantages?\b/i,/\bwhy\s+choose\b/i,/\breasons?\s+to\b/i,/\bvalue\s+proposition\b/i],slideType:"content",bulletStyle:"checkmark"},{patterns:[/\bgoals?\b/i,/\bobjectives?\b/i,/\btargets?\b/i,/\baims?\b/i,/\bour\s+mission\b/i,/\bwhat\s+we\s+aim\s+for\b/i],slideType:"content",bulletStyle:"checkmark"},{patterns:[/\bchallenges?\b/i,/\brisks?\b/i,/\bobstacles?\b/i,/\bbarriers?\b/i,/\bconcerns?\b/i,/\bissues?\b/i,/\bproblems?\b/i],slideType:"content",bulletStyle:"arrow"},{patterns:[/\brequirements?\b/i,/\bchecklist\b/i,/\bprerequisites?\b/i,/\bwhat\s+you\s+need\b/i,/\bmust\s+haves?\b/i,/\bessentials?\b/i],slideType:"content",bulletStyle:"checkmark"}];Wer=[{pattern:/^\d+[.)]\s+/m,bulletStyle:"number"},{pattern:/^step\s+\d+/im,bulletStyle:"number"},{pattern:/^[✓✔☑]\s*/m,bulletStyle:"checkmark"},{pattern:/^\[x\]\s*/im,bulletStyle:"checkmark"},{pattern:/^done:/im,bulletStyle:"checkmark"},{pattern:/^completed:/im,bulletStyle:"checkmark"},{pattern:/^[→➜➡]\s*/m,bulletStyle:"arrow"},{pattern:/^->\s*/m,bulletStyle:"arrow"},{pattern:/^=>\s*/m,bulletStyle:"arrow"}]});function Xer(r,e="content"){return typeof r=="string"&&Jer.has(r)?r:(g.warn(`[ContentPlanner] Invalid slide type "${r}", using "${e}"`),e)}function Yer(r,e){if(typeof r=="string"&&Zer.has(r))return r;let n=qB[e]?.[0]||"title-content";return g.warn(`[ContentPlanner] Invalid layout "${r}" for type "${e}", using "${n}"`),n}function etr(r){if(r&&typeof r=="object"&&"text"in r){let e=r,t={text:String(e.text||"")};return Array.isArray(e.subBullets)&&(t.subBullets=e.subBullets.map(n=>String(n))),typeof e.icon=="string"&&(t.icon=e.icon),typeof e.emphasis=="boolean"&&(t.emphasis=e.emphasis),typeof e.fontSize=="number"&&e.fontSize>=8&&e.fontSize<=48&&(t.fontSize=e.fontSize),typeof e.bulletStyle=="string"&&Qer.has(e.bulletStyle)&&(t.bulletStyle=e.bulletStyle),typeof e.color=="string"&&e.color.match(/^#?[0-9A-Fa-f]{6}$/)&&(t.color=e.color.startsWith("#")?e.color:`#${e.color}`),typeof e.bold=="boolean"&&(t.bold=e.bold),t.text?t:null}return typeof r=="string"&&r.trim()?{text:r.trim()}:null}function YB(r){if(!Array.isArray(r))return[];let e=[];for(let t of r){let n=etr(t);n&&e.push(n)}return e}function ttr(r){if(!r||typeof r!="object")return{};let e=r,t={};if(e.bullets&&(t.bullets=YB(e.bullets)),e.leftColumn&&typeof e.leftColumn=="object"){let o=e.leftColumn;t.leftColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?YB(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(e.rightColumn&&typeof e.rightColumn=="object"){let o=e.rightColumn;t.rightColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?YB(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(e.centerColumn&&typeof e.centerColumn=="object"){let o=e.centerColumn;t.centerColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?YB(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}let n=["subtitle","body","sectionNumber","quote","quoteAuthor","quoteAuthorTitle","caption","galleryImages","statistics","chartData","tableData","timeline","processSteps","features","icons","teamMembers","comparison","nextSteps","cta","ctaButton","contactInfo","layoutOptions","dashboard"];for(let o of n)e[o]!==void 0&&(t[o]=e[o]);return t}function rtr(r,e){if(!r||typeof r!="object")throw new ki("AI returned invalid response: expected object",pl.INVALID_AI_RESPONSE,{received:typeof r});let t=r;if(typeof t.title!="string"||!t.title.trim())throw new ki("AI response missing valid 'title' field",pl.INVALID_AI_RESPONSE,{field:"title",received:t.title});if(!Array.isArray(t.slides))throw new ki("AI response missing 'slides' array",pl.INVALID_AI_RESPONSE,{field:"slides",received:typeof t.slides});t.slides.length!==e&&g.warn(`[ContentPlanner] AI returned ${t.slides.length} slides, expected ${e}. Adjusting...`);let n=[];for(let o=0;o<t.slides.length;o++){let s=t.slides[o];if(!s||typeof s!="object")throw new ki(`Invalid slide at index ${o}`,pl.INVALID_AI_RESPONSE,{index:o,received:typeof s});typeof s.title!="string"&&(s.title=`Slide ${o+1}`,g.warn(`[ContentPlanner] Slide ${o+1} missing title, using default`));let i=Xer(s.type,"content"),a=ttr(s.content),{type:l,bulletStyle:u,wasInferred:d}=D1e(s.title,i,a),p=d&&l!==i?l:i;d&&l!==i&&g.debug(`[ContentPlanner] Slide ${o+1} type inferred from title: "${s.title}" \u2192 ${p}`);let m=L1e(a,u),f=Yer(s.layout,p);typeof s.speakerNotes!="string"&&(s.speakerNotes=""),s.imagePrompt!==null&&typeof s.imagePrompt!="string"&&(s.imagePrompt=null),n.push({slideNumber:o+1,type:p,layout:f,title:s.title,content:m,imagePrompt:s.imagePrompt,speakerNotes:s.speakerNotes})}return{title:t.title,totalSlides:n.length,audience:t.audience||"general",tone:t.tone||"professional",theme:t.theme||"modern",slides:n,keyMessages:Array.isArray(t.keyMessages)?t.keyMessages:void 0}}function ntr(r){let e=r.trim();e.startsWith("```")&&(e=e.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""));try{return JSON.parse(e)}catch(t){throw new ki(`Failed to parse AI response as JSON: ${t instanceof Error?t.message:String(t)}`,pl.INVALID_AI_RESPONSE,{contentPreview:r.substring(0,500),parseError:t instanceof Error?t.message:String(t)})}}async function U1e(r,e){let t=Date.now(),n=`session-${Date.now()}`;g.info("[ContentPlanner] Starting content planning",{topic:r.topic.substring(0,100),pages:r.pages,audience:r.audience,tone:r.tone,theme:r.theme,generateAIImages:r.generateAIImages,provider:r.provider,model:r.model,sessionId:n});let o=jee({topic:r.topic,pages:r.pages,audience:r.audience,tone:r.tone,theme:r.theme,generateAIImages:r.generateAIImages,modelInfo:{name:r.model||"unknown",provider:r.provider||"auto-selected"}});try{let s=await e.generate({prompt:o,systemPrompt:Bee,temperature:.7,maxTokens:8192,disableTools:!0,timeout:Hee});if(!s||!s.content)throw new ki("AI provider returned empty response",pl.PLANNING_FAILED,{provider:r.provider});let i=Date.now()-t;g.debug("[ContentPlanner] AI response received",{contentLength:s.content.length,planningTime:i});let a=ntr(s.content),l=rtr(a,r.pages);return g.info("[ContentPlanner] Content plan generated successfully",{title:l.title,totalSlides:l.totalSlides,planningTime:i,keyMessages:l.keyMessages?.length||0}),l}catch(s){if(s instanceof ki)throw s;let i=s instanceof Error?s.message:String(s);throw new ki(`Content planning failed: ${i}`,pl.PLANNING_FAILED,{topic:r.topic.substring(0,100),provider:r.provider},s instanceof Error?s:void 0)}}function otr(r){return r.slides.length>0&&r.slides[0].type!=="title"&&(r.slides[0]={...r.slides[0],type:"title",layout:"title-centered"}),r}function str(r){let e=r.slides.length-1;return e>=0&&r.slides[e].type!=="thank-you"&&(r.slides[e]={...r.slides[e],type:"thank-you",layout:"contact-info"}),r}function $1e(r){let e={...r,slides:[...r.slides]};return e=otr(e),e=str(e),e}var Jer,Zer,Qer,z1e=A(()=>{"use strict";GB();Ov();F1e();Q();Jer=new Set(["title","section-header","thank-you","closing","content","agenda","bullets","numbered-list","image-focus","image-left","image-right","full-bleed-image","gallery","two-column","three-column","split-content","table","chart-bar","chart-line","chart-pie","chart-area","statistics","quote","timeline","process-flow","comparison","features","team","icons","conclusion","blank","dashboard","mixed-content","stats-grid","icon-grid"]),Zer=new Set(["title-centered","title-bottom","title-left-aligned","title-content","title-content-footer","content-only","image-left-content-right","image-right-content-left","image-top-content-bottom","image-bottom-content-top","image-full-overlay","image-centered","image-grid-2x2","two-column-equal","two-column-wide-left","two-column-wide-right","three-column-equal","chart-full","chart-with-bullets","table-full","table-with-notes","quote-centered","quote-with-image","statistics-row","statistics-grid","timeline-horizontal","timeline-vertical","process-horizontal","process-vertical","comparison-side-by-side","comparison-table","team-grid","icon-grid","summary-bullets","contact-info","blank-full"]);Qer=new Set(["disc","number","checkmark","arrow","dash","none"])});var B1e={};le(B1e,{generatePresentation:()=>itr});async function itr(r){let e=xe.createSpan("ppt.generation","ppt.orchestrate",{"ppt.operation":"orchestrate","ppt.slideCount":r.context.pages,"ppt.theme":typeof r.context.theme=="string"?r.context.theme:"custom"}),t={startTime:Date.now(),contentPlan:null,slides:null,outputPath:null},{context:n,provider:o,providerName:s,modelName:i,neurolink:a,imageProvider:l,imageModel:u}=r;g.info("[PresentationOrchestrator] Starting presentation generation",{topic:n.topic.substring(0,100),pages:n.pages,theme:n.theme,audience:n.audience,tone:n.tone,generateAIImages:n.generateAIImages,provider:n.provider});try{g.info("[PresentationOrchestrator] Step 1: Content planning...");let d=await Oe(U1e(n,o),Kl/2,pe.toolTimeout("contentPlanning",Kl/2));t.contentPlan=$1e(d),e.attributes["ppt.slideCount"]=t.contentPlan.totalSlides,e.attributes["ppt.theme"]=typeof t.contentPlan.theme=="string"?t.contentPlan.theme:"custom",g.info("[PresentationOrchestrator] Content plan ready",{title:t.contentPlan.title,totalSlides:t.contentPlan.totalSlides,theme:t.contentPlan.theme,audience:t.contentPlan.audience,tone:t.contentPlan.tone}),g.info("[PresentationOrchestrator] Step 2: Generating slides...");let p=n.logo??null,m=Xee(p),h={theme:t.contentPlan.theme||n.theme,generateAIImages:n.generateAIImages,aspectRatio:n.aspectRatio,provider:l??n.provider??"vertex",imageModel:u??"gemini-2.5-flash-image",logo:m??void 0,userImages:n.images,neurolink:a},y=new XB(h),v=await Oe(y.generateSlides(t.contentPlan.slides),Kl/2,pe.toolTimeout("slideGeneration",Kl/2));t.slides=v.slides,g.info("[PresentationOrchestrator] Slides generated",{totalSlides:t.slides.length,totalImages:v.totalImages,failedImages:v.failedImages,generationTime:v.generationTime}),g.info("[PresentationOrchestrator] Step 3: Assembling PPTX...");let b=await O1e(),S=new b;S.title=t.contentPlan.title,S.subject=`Generated presentation about: ${n.topic.substring(0,100)}`,S.author="NeuroLink PPT Generator",S.company="NeuroLink",S.layout=Yee(n.aspectRatio);let w=[...t.slides].sort((M,N)=>M.slideNumber-N.slideNumber);for(let M=0;M<w.length;M++){let N=w[M];y.renderSlide(S,N,M+1,w.length)}g.info("[PresentationOrchestrator] PPTX assembled",{totalSlides:w.length,layout:S.layout,title:S.title}),g.info("[PresentationOrchestrator] Step 4: Writing file..."),t.outputPath=Jee(n),await Oe(Zee(t.outputPath),Kl/4,pe.toolTimeout("outputDirectory",Kl/4)),await Oe(S.writeFile({fileName:t.outputPath}),Kl/4,pe.toolTimeout("pptxWrite",Kl/4));let _=0;try{_=(await Oe(Lk(t.outputPath),Kl/8,pe.toolTimeout("pptxStat",Kl/8))).size}catch{g.warn("[PresentationOrchestrator] Could not get file size")}let C=Date.now()-t.startTime;g.info("[PresentationOrchestrator] Presentation generation complete",{filePath:t.outputPath,fileSize:_,totalSlides:w.length,totalTime:C});let R=xe.endSpan(e,1);Ue().recordSpan(R),a?.recordMetricsSpan(R);let I=t.contentPlan?.theme||n.theme,k=t.contentPlan?.audience||n.audience,E=t.contentPlan?.tone||n.tone;return{filePath:t.outputPath,totalSlides:w.length,format:"pptx",provider:s,model:i,metadata:{theme:I,audience:k,tone:E,imageModel:n.generateAIImages?u??"gemini-2.5-flash-image":"",fileSize:_>0?_:0}}}catch(d){let p=xe.endSpan(e,2);if(p.statusMessage=d instanceof Error?d.message:String(d),Ue().recordSpan(p),a?.recordMetricsSpan(p),d instanceof ki)throw g.error("[PresentationOrchestrator] Generation failed",{error:d.message,code:d.code,context:d.context}),d;let m=Qee(d);throw g.error("[PresentationOrchestrator] Unexpected error",{error:m.message,stage:HB(t)}),new ki(`Presentation generation failed: ${m.message}`,pl.ASSEMBLY_FAILED,{topic:n.topic.substring(0,100),stage:HB(t),elapsedTime:Date.now()-t.startTime},m)}}var j1e=A(async()=>{"use strict";await nte();Pu();GB();z1e();await nte();Ov();Q();bt();bo();KB()});var vp,Lw,QB=A(()=>{"use strict";xs();dr();Q();vp=class extends _r{config;pendingRequests=new Map;constructor(e={}){super(),this.config={defaultTimeout:e.defaultTimeout??6e4,enabled:e.enabled??!0,handler:e.handler??this.defaultHandler.bind(this),fallbackBehavior:e.fallbackBehavior??"timeout"}}setHandler(e){this.config.handler=e}setEnabled(e){if(this.config.enabled=e,!e)for(let[t,n]of this.pendingRequests)n.settled||(n.settled=!0,this.handleDisabled(n.request,n.resolve),n.timer&&clearTimeout(n.timer),this.pendingRequests.delete(t))}isEnabled(){return this.config.enabled}async request(e){let t={...e,id:e.id??Fe()};if(!this.config.enabled)return this.handleDisabledRequest(t);let n=t.timeout??this.config.defaultTimeout;return new Promise(o=>{let s=setTimeout(()=>{let i=this.pendingRequests.get(t.id);!i||i.settled||(i.settled=!0,this.handleTimeout(t,o))},n);this.pendingRequests.set(t.id,{request:t,resolve:o,timer:s,settled:!1}),this.emit("elicitationRequested",t),Promise.resolve().then(()=>this.config.handler(t)).then(i=>{let a=this.pendingRequests.get(t.id);!a||a.settled||(a.settled=!0,clearTimeout(s),this.pendingRequests.delete(t.id),this.emit("elicitationResponded",i),o(i))}).catch(i=>{let a=this.pendingRequests.get(t.id);if(!a||a.settled)return;a.settled=!0,clearTimeout(s),this.pendingRequests.delete(t.id);let l={requestId:t.id,responded:!1,error:i instanceof Error?i.message:String(i),timestamp:Date.now()};this.emit("elicitationError",{request:t,error:i}),o(l)})})}async confirm(e,t){let n={type:"confirmation",message:e,toolName:t?.toolName??"unknown",serverId:t?.serverId,confirmLabel:t?.confirmLabel,cancelLabel:t?.cancelLabel,timeout:t?.timeout};return(await this.request(n)).value===!0}async getText(e,t){let n={type:"text",message:e,toolName:t?.toolName??"unknown",placeholder:t?.placeholder,defaultValue:t?.defaultValue,timeout:t?.timeout};return(await this.request(n)).value}async select(e,t,n){let o={type:"select",message:e,toolName:n?.toolName??"unknown",options:t,timeout:n?.timeout};return(await this.request(o)).value}async multiSelect(e,t,n){let o={type:"multiselect",message:e,toolName:n?.toolName??"unknown",options:t,timeout:n?.timeout,minSelections:n?.minSelections,maxSelections:n?.maxSelections};return(await this.request(o)).value}async form(e,t,n){let o={type:"form",message:e,toolName:n?.toolName??"unknown",serverId:n?.serverId,fields:t,submitLabel:n?.submitLabel,timeout:n?.timeout};return(await this.request(o)).value}async getSecret(e,t){let n={type:"secret",message:e,toolName:t?.toolName??"unknown",hint:t?.hint,timeout:t?.timeout};return(await this.request(n)).value}cancel(e,t){let n=this.pendingRequests.get(e);if(n){if(n.settled)return;n.settled=!0,n.timer&&clearTimeout(n.timer);let o={requestId:e,responded:!1,cancelled:!0,error:t,timestamp:Date.now()};n.resolve(o),this.pendingRequests.delete(e),this.emit("elicitationCancelled",{requestId:e,reason:t})}}async defaultHandler(e){return g.warn(`[ElicitationManager] No handler for elicitation request: ${e.id}`),e.defaultValue!==void 0?{requestId:e.id,responded:!0,value:e.defaultValue,timestamp:Date.now()}:{requestId:e.id,responded:!1,error:"No elicitation handler configured",timestamp:Date.now()}}handleTimeout(e,t){this.pendingRequests.delete(e.id);let n={requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()};this.emit("elicitationTimeout",{request:e}),t(n)}handleDisabled(e,t){t(this.handleDisabledRequest(e))}handleDisabledRequest(e){switch(this.config.fallbackBehavior){case"default":return{requestId:e.id,responded:e.defaultValue!==void 0,value:e.defaultValue,timestamp:Date.now()};case"error":return{requestId:e.id,responded:!1,error:"Elicitation is disabled",timestamp:Date.now()};default:return{requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()}}}getPendingCount(){return this.pendingRequests.size}getPendingRequests(){return Array.from(this.pendingRequests.values()).map(e=>e.request)}clearPending(e){for(let[t]of this.pendingRequests)this.cancel(t,e??"Cleared")}},Lw=new vp});var q1e={};le(q1e,{ElicitationManager:()=>vp,globalElicitationManager:()=>Lw});var ote=A(()=>{"use strict";QB()});var V1e={};le(V1e,{MCPRegistryClient:()=>Fw,getAllWellKnownServers:()=>ate,getWellKnownServer:()=>ite,globalMCPRegistryClient:()=>ste});function ite(r){return ej.find(e=>e.id===r)}function ate(){return[...ej]}var ej,Fw,ste,cte=A(()=>{"use strict";xs();ej=[{id:"filesystem",name:"Filesystem",description:"File system operations - read, write, create, list directories",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem"],transports:["stdio"],categories:["file-system"],tags:["files","directories","read","write"],tools:["read_file","write_file","list_directory","create_directory"],verified:!0},{id:"github",name:"GitHub",description:"GitHub repository management and file operations",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],requiredEnvVars:["GITHUB_PERSONAL_ACCESS_TOKEN"],transports:["stdio"],categories:["version-control","api"],tags:["github","git","repositories","issues","pull-requests"],tools:["create_repository","list_commits","create_issue","create_pull_request"],verified:!0},{id:"postgres",name:"PostgreSQL",description:"PostgreSQL database query and management",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres"],requiredEnvVars:["DATABASE_URL"],transports:["stdio"],categories:["database"],tags:["postgres","postgresql","sql","database","query"],tools:["query","list_tables","describe_table"],verified:!0},{id:"sqlite",name:"SQLite",description:"SQLite database operations and queries",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite"],transports:["stdio"],categories:["database"],tags:["sqlite","sql","database","local"],tools:["query","list_tables","describe_table"],verified:!0},{id:"brave-search",name:"Brave Search",description:"Web search using Brave Search API",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-brave-search",command:"npx",args:["-y","@modelcontextprotocol/server-brave-search"],requiredEnvVars:["BRAVE_API_KEY"],transports:["stdio"],categories:["search","api"],tags:["search","web","brave","internet"],tools:["web_search","local_search"],verified:!0},{id:"puppeteer",name:"Puppeteer",description:"Web scraping and browser automation",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-puppeteer",command:"npx",args:["-y","@modelcontextprotocol/server-puppeteer"],transports:["stdio"],categories:["automation","web"],tags:["browser","scraping","automation","puppeteer"],tools:["navigate","screenshot","click","type","get_content"],verified:!0},{id:"git",name:"Git",description:"Git repository operations and version control",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-git",command:"npx",args:["-y","@modelcontextprotocol/server-git"],transports:["stdio"],categories:["version-control"],tags:["git","vcs","commits","branches"],tools:["git_status","git_log","git_diff","git_commit"],verified:!0},{id:"memory",name:"Memory",description:"Persistent memory and knowledge storage",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-memory",command:"npx",args:["-y","@modelcontextprotocol/server-memory"],transports:["stdio"],categories:["memory","storage"],tags:["memory","knowledge","storage","persistent"],tools:["store","retrieve","search","delete"],verified:!0},{id:"slack",name:"Slack",description:"Slack workspace integration",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],requiredEnvVars:["SLACK_BOT_TOKEN"],transports:["stdio"],categories:["communication","api"],tags:["slack","messaging","chat","team"],tools:["send_message","list_channels","get_channel_history"],verified:!0},{id:"google-drive",name:"Google Drive",description:"Google Drive file management",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-gdrive",command:"npx",args:["-y","@modelcontextprotocol/server-gdrive"],transports:["stdio"],categories:["file-system","api"],tags:["google","drive","files","cloud"],tools:["list_files","read_file","create_file","search_files"],verified:!0}],Fw=class extends _r{config;cache=new Map;customEntries=new Map;constructor(e={}){super(),this.config={registries:e.registries??[{type:"official",enableCache:!0}],enableCache:e.enableCache??!0,defaultCacheTTL:e.defaultCacheTTL??36e5,timeout:e.timeout??1e4,userAgent:e.userAgent??"NeuroLink-MCP-Registry-Client/1.0"}}async search(e={}){let{query:t,categories:n,tags:o,transport:s,verifiedOnly:i=!1,sortBy:a="downloads",sortDirection:l="desc",limit:u=25,offset:d=0}=e,p=Math.max(1,u),m=Math.max(0,d),f=await this.getAllEntries();if(t){let y=t.toLowerCase();f=f.filter(v=>v.name.toLowerCase().includes(y)||v.description.toLowerCase().includes(y)||v.tags?.some(b=>b.toLowerCase().includes(y)))}n?.length&&(f=f.filter(y=>y.categories?.some(v=>n.includes(v)))),o?.length&&(f=f.filter(y=>y.tags?.some(v=>o.includes(v)))),s&&(f=f.filter(y=>y.transports?.includes(s))),i&&(f=f.filter(y=>y.verified)),f.sort((y,v)=>{let b=0;switch(a){case"name":b=y.name.localeCompare(v.name);break;case"downloads":b=(y.downloads??0)-(v.downloads??0);break;case"stars":b=(y.stars??0)-(v.stars??0);break;case"lastUpdated":b=(y.lastUpdated??"").localeCompare(v.lastUpdated??"");break}return l==="desc"?-b:b});let h=f.length;return f=f.slice(m,m+p),{entries:f,totalCount:h,page:Math.floor(m/p)+1,pageSize:p,hasMore:m+f.length<h}}async getEntry(e){if(this.customEntries.has(e))return this.customEntries.get(e);let t=ej.find(n=>n.id===e);if(t)return t}async getAllEntries(){let e="all-entries";if(this.config.enableCache){let o=this.cache.get(e);if(o&&Date.now()-o.timestamp<this.config.defaultCacheTTL)return o.data}let t=new Set(this.customEntries.keys()),n=[...ej.filter(o=>!t.has(o.id)),...Array.from(this.customEntries.values())];return this.config.enableCache&&this.cache.set(e,{data:n,timestamp:Date.now()}),n}async getByCategory(e){return(await this.getAllEntries()).filter(n=>n.categories?.includes(e))}async getByTag(e){return(await this.getAllEntries()).filter(n=>n.tags?.includes(e))}async getCategories(){let e=await this.getAllEntries(),t=new Set;for(let n of e)for(let o of n.categories??[])t.add(o);return Array.from(t).sort()}async getTags(){let e=await this.getAllEntries(),t=new Set;for(let n of e)for(let o of n.tags??[])t.add(o);return Array.from(t).sort()}toServerInfo(e){return{id:e.id,name:e.name,description:e.description,command:e.command,args:e.args,transport:e.transports?.[0]??"stdio",status:"stopped",tools:e.tools?.map(t=>({name:t,description:`Tool: ${t}`}))??[],metadata:{...e.metadata,version:e.version,author:e.author,license:e.license,homepage:e.homepage,repository:e.repository,npmPackage:e.npmPackage,requiredEnvVars:e.requiredEnvVars,categories:e.categories,tags:e.tags,verified:e.verified}}}addCustomEntry(e){this.customEntries.set(e.id,e),this.clearCache(),this.emit("entryAdded",{entry:e})}removeCustomEntry(e){let t=this.customEntries.delete(e);return t&&(this.clearCache(),this.emit("entryRemoved",{id:e})),t}addRegistry(e){this.config.registries.push(e),this.clearCache();let{authToken:t,...n}=e;this.emit("registryAdded",{config:n})}clearCache(){this.cache.clear(),this.emit("cacheCleared")}checkRequiredEnvVars(e){let t=[];for(let n of e.requiredEnvVars??[])process.env[n]||t.push(n);return{ready:t.length===0,missing:t}}getInstallCommand(e){if(e.installCommand)return e.installCommand;if(e.npmPackage)return`npx -y ${e.npmPackage}`}async getPopularServers(e=10){return(await this.search({sortBy:"downloads",sortDirection:"desc",limit:e})).entries}async getVerifiedServers(){return(await this.search({verifiedOnly:!0})).entries}async getStatistics(){let e=await this.getAllEntries(),t=await this.getCategories(),n=await this.getTags();return{totalEntries:e.length,verifiedEntries:e.filter(o=>o.verified).length,categories:t.length,tags:n.length,customEntries:this.customEntries.size}}},ste=new Fw});var pte={};le(pte,{AgentExposureManager:()=>Uw,exposeAgentAsTool:()=>qA,exposeAgentsAsTools:()=>lte,exposeWorkflowAsTool:()=>VA,exposeWorkflowsAsTools:()=>ute,globalAgentExposureManager:()=>dte});function qA(r,e={}){let{prefix:t="agent",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:s=v=>v.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:i=!0,executionTimeout:a=3e5,enableLogging:l=!0}=e,u=s(r.name),d=t?`${t}_${u}`:u,p=r.description;if(o&&r.metadata){let v=[];r.metadata.version&&v.push(`v${r.metadata.version}`),r.metadata.category&&v.push(`category: ${r.metadata.category}`),r.metadata.estimatedDuration&&v.push(`~${r.metadata.estimatedDuration}ms`),v.length>0&&(p+=` [${v.join(", ")}]`)}let m={...n,complexity:n.complexity??"complex",estimatedDuration:r.metadata?.estimatedDuration??n.estimatedDuration,costHint:r.metadata?.costHint??n.costHint,tags:[...n.tags??[],"agent",...r.metadata?.tags??[]]},f=r.inputSchema??{type:"object",properties:{}},h=async(v,b)=>{let S=Date.now();l&&g.debug(`[AgentExposure] Executing agent '${r.id}' as tool '${d}'`);try{let w=b?.config&&typeof b.config=="object"?b.config:{},_=i?{...b,config:{...w,sourceType:"mcp-exposed-agent",agentId:r.id,toolName:d}}:b??{},C=await Mn(r.execute(v,_),a),R=Date.now()-S;return l&&g.debug(`[AgentExposure] Agent '${r.id}' completed in ${R}ms`),{success:!0,data:C,metadata:{agentId:r.id,toolName:d,executionTime:R,sourceType:"agent"}}}catch(w){let _=Date.now()-S,C=w instanceof Error?w:pe.toolExecutionFailed(d,new Error(String(w)));return l&&g.error(`[AgentExposure] Agent '${r.id}' failed after ${_}ms: ${C.message}`),{success:!1,error:C.message,metadata:{agentId:r.id,toolName:d,executionTime:_,sourceType:"agent"}}}};return{tool:{name:d,description:p,inputSchema:f,outputSchema:r.outputSchema,annotations:m,execute:h,metadata:{sourceType:"agent",sourceId:r.id,originalName:r.name,...r.metadata}},sourceType:"agent",sourceId:r.id,toolName:d}}function VA(r,e={}){let{prefix:t="workflow",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:s=v=>v.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:i=!0,executionTimeout:a=6e5,enableLogging:l=!0}=e,u=s(r.name),d=t?`${t}_${u}`:u,p=r.description;if(o){let v=[];r.metadata?.version&&v.push(`v${r.metadata.version}`),r.steps?.length&&v.push(`${r.steps.length} steps`),r.metadata?.estimatedDuration&&v.push(`~${r.metadata.estimatedDuration}ms`),v.length>0&&(p+=` [${v.join(", ")}]`)}let m={...n,complexity:n.complexity??"complex",estimatedDuration:r.metadata?.estimatedDuration??n.estimatedDuration,idempotentHint:r.metadata?.idempotent??n.idempotentHint,tags:[...n.tags??[],"workflow",...r.metadata?.tags??[]]},f=r.inputSchema??{type:"object",properties:{}},h=async(v,b)=>{let S=Date.now();l&&g.debug(`[WorkflowExposure] Executing workflow '${r.id}' as tool '${d}'`);try{let w=b?.config&&typeof b.config=="object"?b.config:{},_=i?{...b,config:{...w,sourceType:"mcp-exposed-workflow",workflowId:r.id,toolName:d}}:b??{},C=await Mn(r.execute(v,_),a),R=Date.now()-S;return l&&g.debug(`[WorkflowExposure] Workflow '${r.id}' completed in ${R}ms`),{success:!0,data:C,metadata:{workflowId:r.id,toolName:d,executionTime:R,sourceType:"workflow",stepsCount:r.steps?.length}}}catch(w){let _=Date.now()-S,C=w instanceof Error?w:pe.toolExecutionFailed(d,new Error(String(w)));return l&&g.error(`[WorkflowExposure] Workflow '${r.id}' failed after ${_}ms: ${C.message}`),{success:!1,error:C.message,metadata:{workflowId:r.id,toolName:d,executionTime:_,sourceType:"workflow"}}}};return{tool:{name:d,description:p,inputSchema:f,outputSchema:r.outputSchema,annotations:m,execute:h,metadata:{sourceType:"workflow",sourceId:r.id,originalName:r.name,steps:r.steps,...r.metadata}},sourceType:"workflow",sourceId:r.id,toolName:d}}function lte(r,e={}){return r.map(t=>qA(t,e))}function ute(r,e={}){return r.map(t=>VA(t,e))}var Uw,dte,tj=A(()=>{"use strict";Q();Vl();bt();Uw=class{exposedTools=new Map;options;constructor(e={}){this.options=e}exposeAgent(e){let t=qA(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}exposeWorkflow(e){let t=VA(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}getExposedTools(){return Array.from(this.exposedTools.values()).map(e=>e.tool)}getExposedTool(e){return this.exposedTools.get(e)?.tool}getExposureResult(e){return this.exposedTools.get(e)}getToolsBySourceType(e){return Array.from(this.exposedTools.values()).filter(t=>t.sourceType===e).map(t=>t.tool)}unexpose(e){return this.exposedTools.delete(e)}clear(){this.exposedTools.clear()}getStatistics(){let e=Array.from(this.exposedTools.values());return{totalExposed:e.length,exposedAgents:e.filter(t=>t.sourceType==="agent").length,exposedWorkflows:e.filter(t=>t.sourceType==="workflow").length,toolNames:e.map(t=>t.toolName)}}},dte=new Uw});var G1e={};le(G1e,{ToolIntegrationManager:()=>$w,confirmationMiddleware:()=>gte,createElicitationContext:()=>GA,createRetryMiddleware:()=>yte,createTimeoutMiddleware:()=>hte,createToolMiddlewareChain:()=>rj,globalToolIntegrationManager:()=>xte,loggingMiddleware:()=>fte,validationMiddleware:()=>vte,wrapToolWithElicitation:()=>HA,wrapToolsWithElicitation:()=>mte});function GA(r,e,t){return{confirm:async(n,o)=>t.confirm(n,{toolName:r,serverId:e,confirmLabel:o?.confirmLabel,cancelLabel:o?.cancelLabel}),getText:async(n,o)=>t.getText(n,{toolName:r,placeholder:o?.placeholder,defaultValue:o?.defaultValue}),select:async(n,o)=>t.select(n,o,{toolName:r}),multiSelect:async(n,o)=>t.multiSelect(n,o,{toolName:r}),form:async(n,o)=>t.form(n,o,{toolName:r,serverId:e}),request:async n=>t.request({...n,toolName:r,serverId:e})}}function HA(r,e={}){let{elicitationManager:t,autoConfirmDestructive:n=!1,elicitationTimeout:o=6e4,enableLogging:s=!0}=e,i=t??new vp({defaultTimeout:o});return{...r,execute:async(a,l)=>{let d=l?.config?.serverId,p=GA(r.name,d,i);if((r.annotations?.requiresConfirmation||r.annotations?.destructiveHint)&&!n&&(s&&g.debug(`[ToolIntegration] Tool '${r.name}' requires confirmation`),!await p.confirm(`This operation (${r.name}) ${r.annotations?.destructiveHint?"is destructive and ":""}requires confirmation. Do you want to proceed?`,{confirmLabel:"Yes, proceed",cancelLabel:"Cancel"})))return{success:!1,error:"Operation cancelled by user",metadata:{toolName:r.name,cancelled:!0}};let f={...l,elicitation:p,toolMeta:{name:r.name,serverId:d,annotations:r.annotations}};return r.execute(a,f)}}}function mte(r,e={}){return r.map(t=>HA(t,e))}function rj(r){return async(e,t,n,o)=>{let s=async i=>{if(i>=r.length)return o();let a=r[i];return a(e,t,n,()=>s(i+1))};return s(0)}}function hte(r){return async(e,t,n,o)=>Oe(o(),r,pe.toolTimeout(e.name,r))}function yte(r,e=1e3){return async(t,n,o,s)=>{if(!(t.annotations?.idempotentHint||t.annotations?.readOnlyHint))return s();let a=Math.max(0,r),l;for(let u=0;u<=a;u++)try{return await s()}catch(d){l=d instanceof Error?d:pe.toolExecutionFailed(t.name,new Error(String(d))),u<a&&(g.warn(`[ToolMiddleware] Tool '${t.name}' failed, retrying (${u+1}/${a})`),await new Promise(p=>setTimeout(p,e*(u+1))))}throw l??pe.toolExecutionFailed(t.name,new Error("Retry middleware exhausted without captured error"))}}var fte,gte,vte,$w,xte,bte=A(()=>{"use strict";QB();bt();Q();fte=async(r,e,t,n)=>{let o=Date.now();g.debug(`[ToolMiddleware] Executing tool '${r.name}'`);try{let s=await n(),i=Date.now()-o;return g.debug(`[ToolMiddleware] Tool '${r.name}' completed in ${i}ms`),s}catch(s){let i=Date.now()-o;throw g.error(`[ToolMiddleware] Tool '${r.name}' failed after ${i}ms:`,s),s}},gte=async(r,e,t,n)=>t.elicitation?.confirm&&(r.annotations?.destructiveHint||r.annotations?.requiresConfirmation)&&!await t.elicitation.confirm(`Confirm execution of ${r.name}?`)?{success:!1,error:"Operation cancelled by user",metadata:{cancelled:!0}}:n();vte=async(r,e,t,n)=>{if(!r.inputSchema)return n();let o=r.inputSchema,s=o.required??[],i=o.properties??{},a=e??{},l=[];for(let u of s)a[u]===void 0&&l.push(u);if(l.length>0){let u=l.map(p=>{let m=i[p];return{name:p,label:p,type:m?.type??"text",required:!0,description:m?.description}}),d=await t.elicitation.form(`Missing required parameters for ${r.name}`,u);if(!d)return{success:!1,error:`Missing required parameters: ${l.join(", ")}`,metadata:{missingParams:l}};Object.assign(a,d)}return n()},$w=class{elicitationManager;middlewares=[];wrappedTools=new Map;constructor(e){this.elicitationManager=e??new vp}setElicitationHandler(e){this.elicitationManager.setHandler(e)}use(e){return this.middlewares.push(e),this}registerTool(e){let t=HA(e,{elicitationManager:this.elicitationManager});return this.wrappedTools.set(e.name,t),t}async executeTool(e,t,n){let o=this.wrappedTools.get(e);if(!o)throw pe.toolNotFound(e,Array.from(this.wrappedTools.keys()));let s=t&&typeof t=="object"?t:{},a=n?.config?.serverId,l=GA(e,a,this.elicitationManager),u={...n,elicitation:l,toolMeta:{name:e,serverId:a,annotations:o.annotations}};return this.middlewares.length===0?o.execute(s,u):rj(this.middlewares)(o,s,u,()=>o.execute(s,u))}getTool(e){return this.wrappedTools.get(e)}getAllTools(){return Array.from(this.wrappedTools.values())}getElicitationManager(){return this.elicitationManager}},xte=new $w});var Ate={};le(Ate,{TOOL_COMPATIBILITY:()=>Rte,batchConvertToMCP:()=>wte,batchConvertToNeuroLink:()=>_te,createToolFromFunction:()=>Ete,mcpProtocolToolToServerTool:()=>Tte,mcpToolToNeuroLink:()=>oj,neuroLinkToolToMCP:()=>nj,sanitizeToolName:()=>kte,serverToolToMCPProtocol:()=>Ste,validateToolName:()=>Cte});function nj(r,e={}){let{inferAnnotations:t=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=e,i=s?`${s}_${r.name}`:r.name,a=t?ul({name:r.name,description:r.description}):{},l={...n,...a};r.tags?.length&&(l.tags=[...new Set([...l.tags??[],...r.tags])]);let u=r.parameters??{type:"object",properties:{}},d=o?{...r.metadata}:{};return r.category&&(d.category=r.category),r.isAsync!==void 0&&(d.isAsync=r.isAsync),{name:i,description:r.description,inputSchema:u,annotations:l,execute:r.execute,metadata:d}}function oj(r,e={}){let{removeNamespacePrefix:t}=e,n=r.name;return t&&r.name.startsWith(`${t}_`)&&(n=r.name.slice(t.length+1)),{name:n,description:r.description,parameters:r.inputSchema,execute:r.execute,category:r.metadata?.category,tags:r.annotations?.tags,metadata:r.metadata}}function Tte(r,e,t={}){let{inferAnnotations:n=!0,defaultAnnotations:o={}}=t,s=r.annotations??{},i=n?ul({name:r.name,description:r.description??""}):{},a={...o,...i,title:s.title??i.title??o.title,readOnlyHint:s.readOnlyHint??i.readOnlyHint??o.readOnlyHint,destructiveHint:s.destructiveHint??i.destructiveHint??o.destructiveHint,idempotentHint:s.idempotentHint??i.idempotentHint??o.idempotentHint,openWorldHint:s.openWorldHint??i.openWorldHint??o.openWorldHint};return{name:r.name,description:r.description??"No description provided",inputSchema:r.inputSchema,annotations:a,execute:e}}function Ste(r){let e={};r.annotations?.title&&(e.title=r.annotations.title),r.annotations?.readOnlyHint!==void 0&&(e.readOnlyHint=r.annotations.readOnlyHint),r.annotations?.destructiveHint!==void 0&&(e.destructiveHint=r.annotations.destructiveHint),r.annotations?.idempotentHint!==void 0&&(e.idempotentHint=r.annotations.idempotentHint),r.annotations?.openWorldHint!==void 0&&(e.openWorldHint=r.annotations.openWorldHint);let t=r.inputSchema??{type:"object",properties:{}};return{name:r.name,description:r.description,inputSchema:{type:"object",properties:t.properties??{},required:"required"in t?t.required:void 0},annotations:Object.keys(e).length>0?e:void 0}}function wte(r,e={}){return r.map(t=>nj(t,e))}function _te(r,e={}){return r.map(t=>oj(t,e))}function Ete(r,e,t,n){let o=ul({name:r,description:e});return{name:r,description:e,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await Mn(t(s,i),3e4,`Tool '${r}' execution timed out after 30000ms`),metadata:n?.metadata}}function Cte(r){let e=[];return!r||typeof r!="string"?e.push("Tool name is required and must be a string"):(r.length>64&&e.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(r)||e.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:e.length===0,errors:e}}function kte(r){let e=r.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(e)||(e=`_${e}`),e.length>64&&(e=e.slice(0,64)),e}var Rte,sj=A(()=>{"use strict";JS();Vl();Rte={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}});async function H1e(r){let e=r.url?`url:${r.url.replace(/:\/\/[^:]+:[^@]+@/,"://[redacted]@")}`:`${r.host}:${r.port}:${r.db}:${r.password?"auth":"noauth"}`,t=sd.get(e);if(t&&t.client.isOpen)return t.refCount++,g.debug("[Redis] Reusing pooled connection",{key:e,refCount:t.refCount}),t.client;let n=Ite.get(e);if(n){let s=await n,i=sd.get(e);if(i){if(!i.client.isOpen){sd.delete(e);let a=await Pte(r);return sd.set(e,{client:a,refCount:1}),a}i.refCount++}else if(s.isOpen)sd.set(e,{client:s,refCount:1});else{let a=await Pte(r);return sd.set(e,{client:a,refCount:1}),a}return s}t&&sd.delete(e);let o=Pte(r);Ite.set(e,o);try{let s=await o;return sd.set(e,{client:s,refCount:1}),g.info("[Redis] Created pooled connection",{key:e,refCount:1}),s}finally{Ite.delete(e)}}async function W1e(r){let e=`${r.host}:${r.port}:${r.db}:${r.password?"auth":"noauth"}`,t=sd.get(e);if(t&&(t.refCount--,g.debug("[Redis] Released pooled connection",{key:e,refCount:t.refCount}),t.refCount<=0)){try{t.client.isOpen&&await t.client.quit()}catch(n){g.warn("[Redis] Error closing pooled connection",{key:e,error:String(n)})}sd.delete(e),g.info("[Redis] Closed pooled connection",{key:e})}}function ctr(){return Array.from(sd.entries()).map(([r,e])=>({key:r,refCount:e.refCount,isOpen:e.client.isOpen}))}async function Pte(r){let t={url:r.url||`redis://${r.host}:${r.port}/${r.db}`,socket:{connectTimeout:r.connectionOptions?.connectTimeout,reconnectStrategy:o=>o>(r.connectionOptions?.maxRetriesPerRequest||3)?(g.error("Redis connection retries exhausted"),new Error("Redis connection retries exhausted")):Math.min((r.connectionOptions?.retryDelayOnFailover||100)*2**o,1e4)}};r.password&&!r.url&&(t.password=r.password);let n=kA(t);return n.on("error",o=>{let s=o.message.replace(/redis:\/\/.*?@/g,"redis://[redacted]@");g.error("Redis client error",{error:s})}),n.on("connect",()=>{g.debug("Redis client connected",{host:r.host,port:r.port,db:r.db})}),n.on("reconnecting",()=>{g.debug("Redis client reconnecting")}),n.isOpen||await n.connect(),n}function ml(r,e,t){if(!t)return g.warn("[REDIS] getSessionKey called without userId",{sessionId:e}),`${r.keyPrefix}${atr}${e}`;let n=`${r.keyPrefix}${t}:${e}`;return g.debug("[redisUtils] Generated session key",{sessionId:e,userId:t,keyPrefix:r.keyPrefix,fullKey:n}),n}function ij(r,e){return`${r.userSessionsKeyPrefix}${e}`}function zw(r){try{return JSON.stringify(r)}catch(e){throw g.error("[redisUtils] Failed to serialize conversation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,sessionId:r?.sessionId,userId:r?.userId}),e}}function fl(r){if(!r)return null;try{let e=JSON.parse(String(r));if(typeof e!="object"||e===null||!("title"in e)||!("sessionId"in e)||!("userId"in e)||!("createdAt"in e)||!("updatedAt"in e)||!("messages"in e))return g.warn("[redisUtils] Deserialized data is not a valid conversation object",{type:typeof e,hasRequiredFields:e&&typeof e=="object"?Object.keys(e).join(", "):"none",preview:JSON.stringify(e).substring(0,100)}),null;let t=e;return Array.isArray(t.messages)?t.messages.every(o=>typeof o=="object"&&o!==null&&"role"in o&&"content"in o&&typeof o.role=="string"&&typeof o.content=="string"&&(o.role==="user"||o.role==="assistant"||o.role==="system"||o.role==="tool_call"||o.role==="tool_result"))?(g.debug("[redisUtils] Conversation deserialized successfully",{sessionId:t.sessionId,userId:t.userId,title:t.title,messageCount:t.messages.length,createdAt:t.createdAt,updatedAt:t.updatedAt}),t):(g.warn("[redisUtils] Invalid messages structure",{messageCount:t.messages.length,firstMessage:t.messages.length>0?JSON.stringify(t.messages[0]):null}),null):(g.warn("[redisUtils] messages is not an array",{type:typeof t.messages}),null)}catch(e){return g.error("[redisUtils] Failed to deserialize conversation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,dataLength:r.length,dataPreview:"[REDACTED]"}),null}}async function aj(r,e,t=100){g.debug("[redisUtils] Starting SCAN operation",{pattern:e,batchSize:t});let n=[],o="0",s=0,i=0;try{do{s++;let a=await r.scan(o,{MATCH:e,COUNT:t});o=String(a.cursor);let l=(a.keys||[]).map(String);n.push(...l),i+=l.length,g.debug("[redisUtils] SCAN iteration completed",{iteration:s,currentCursor:o,keysInBatch:l.length,totalKeysFound:n.length})}while(o!=="0");return g.info("[redisUtils] SCAN operation completed",{pattern:e,totalIterations:s,totalKeysFound:n.length,totalScanned:i}),n}catch(a){throw g.error("[redisUtils] Error during SCAN operation",{pattern:e,error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0}),a}}function K1e(r){let e=r.keyPrefix||"neurolink:conversation:",t=e.replace(/conversation:?$/,"user:sessions:"),n=r.host||"localhost",o=r.port||6379,s=r.username||"",i=r.password||"",a=r.db||0,l=r.url;if(l)try{let u=new URL(l);n=u.hostname,o=u.port?parseInt(u.port):6379,s=u.username||s,i=u.password||i,a=u.pathname&&parseInt(u.pathname.replace("/",""))||0}catch(u){let d=l.replace(/:\/\/[^@]+@/,"://[redacted]@");g.warn("[redisUtils] Failed to parse Redis URL, falling back to component-based connection",{url:d,error:u instanceof Error?u.message:String(u)}),l=void 0}return{url:l||"",host:n,port:o,password:i,username:s,db:a,keyPrefix:e,userSessionsKeyPrefix:r.userSessionsKeyPrefix||t,ttl:r.ttl||86400,connectionOptions:{connectTimeout:3e4,lazyConnect:!0,retryDelayOnFailover:100,maxRetriesPerRequest:3,...r.connectionOptions}}}var atr,sd,Ite,Mte=A(()=>{"use strict";SB();Q();atr="session-only:",sd=new Map,Ite=new Map});var WA,Ote,cj,J1e=A(async()=>{"use strict";Kt();tr();dr();O$();BQ();XY();await sz();vr();bt();pv();wm();Q();Mte();WA=ye.redis,Ote=5e3,cj=class{config;isInitialized=!1;summarizationEngine=new WS;redisConfig;redisClient=null;pendingToolExecutions=new Map;titleGenerationInProgress=new Set;summarizationInProgress=new Set;constructor(e,t={}){this.config=e,this.redisConfig=K1e(t)}async initialize(){if(this.isInitialized){g.debug("[RedisConversationMemoryManager] Already initialized, skipping");return}await WA.startActiveSpan("neurolink.memory.initialize",{kind:er.CLIENT,attributes:{"redis.host":this.redisConfig.host,"redis.port":this.redisConfig.port,"redis.key_prefix":this.redisConfig.keyPrefix}},async e=>{try{g.debug("[RedisConversationMemoryManager] Initializing with config",{host:this.redisConfig.host,port:this.redisConfig.port,keyPrefix:this.redisConfig.keyPrefix,ttl:this.redisConfig.ttl}),this.redisClient=await H1e(this.redisConfig),this.isInitialized=!0,g.info("RedisConversationMemoryManager initialized",{storage:"redis",host:this.redisConfig.host,port:this.redisConfig.port,maxSessions:this.config.maxSessions,maxTurnsPerSession:this.config.maxTurnsPerSession}),g.debug("[RedisConversationMemoryManager] Redis client created successfully",{clientType:this.redisClient?.constructor?.name||"unknown",isConnected:!!this.redisClient})}catch(t){throw e.setStatus({code:be.ERROR,message:t instanceof Error?t.message:String(t)}),e.recordException(t instanceof Error?t:new Error(String(t))),g.error("[RedisConversationMemoryManager] Failed to initialize",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,config:{host:this.redisConfig.host,port:this.redisConfig.port}}),new qi("Failed to initialize Redis conversation memory","CONFIG_ERROR",{error:t instanceof Error?t.message:String(t)})}finally{e.end()}})}get canPersist(){return this.isInitialized&&this.redisClient!==null&&this.redisClient.isOpen}get isRedisConfigured(){return this.redisClient!==null&&this.redisClient.isOpen}getHealthStatus(){return{initialized:this.isInitialized,connected:this.redisClient?.isOpen??!1,host:this.redisConfig.host,keyPrefix:this.redisConfig.keyPrefix}}async getSession(e,t,n){if(await this.ensureInitialized(),!this.redisClient)return;let o=this.redisClient;return WA.startActiveSpan("neurolink.memory.getSession",{kind:er.CLIENT,attributes:{"session.id":e}},async s=>{t&&s.setAttribute("user.id",t);try{let i=ml(this.redisConfig,e,t),a=await Oe(o.get(i),Ote),l=fl(a||null);if(!l){s.setAttribute("session.found",!1);return}s.setAttribute("session.found",!0);let u=a?Buffer.byteLength(a,"utf8"):0,d=l.messages.length,p=!!l.summarizedUpToMessageId,m=p?l.messages.findIndex(h=>h.id===l.summarizedUpToMessageId):-1,f=p&&m!==-1?d-m-1:d;return s.setAttribute("message.count",d),s.setAttribute("blob.size_bytes",u),g.info("[ConversationMemory] Session loaded",{requestId:n,sessionId:e,blobSizeBytes:u,messageCount:d,hasSummary:p,recentMessageCount:f}),u>512*1024&&g.warn("[ConversationMemory] Large session blob",{requestId:n,sessionId:e,blobSizeBytes:u,messageCount:d}),{sessionId:l.sessionId,userId:l.userId,messages:l.messages,summarizedUpToMessageId:l.summarizedUpToMessageId,summarizedMessage:l.summarizedMessage,tokenThreshold:l.tokenThreshold,lastTokenCount:l.lastTokenCount,lastCountedAt:l.lastCountedAt,lastApiTokenCount:l.lastApiTokenCount,createdAt:new Date(l.createdAt).getTime(),lastActivity:new Date(l.updatedAt).getTime()}}catch(i){s.setStatus({code:be.ERROR,message:i instanceof Error?i.message:String(i)}),s.recordException(i instanceof Error?i:new Error(String(i))),g.error("[RedisConversationMemoryManager] Failed to get session",{sessionId:e,userId:t,error:i instanceof Error?i.message:String(i)});return}finally{s.end()}})}async getSessionRaw(e,t){try{if(await this.ensureInitialized(),!this.redisClient)return null;let n=ml(this.redisConfig,e,t),o=await this.redisClient.get(n);return fl(o||null)}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get raw session",{sessionId:e,userId:t,error:n instanceof Error?n.message:String(n)}),null}}async getUserSessions(e){if(await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];try{let t=ij(this.redisConfig,e),n=await this.redisClient.sMembers(t);return Array.from(n).map(String)}catch(t){return g.error("[RedisConversationMemoryManager] Failed to get user sessions",{userId:e,error:t instanceof Error?t.message:String(t)}),[]}}async addUserSession(e,t){if(!(!this.redisClient||!e))try{let n=ij(this.redisConfig,e);await this.redisClient.sAdd(n,t),this.redisConfig.ttl>0&&await this.redisClient.expire(n,this.redisConfig.ttl)}catch(n){g.error("[RedisConversationMemoryManager] Failed to add session to user set",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n)})}}async removeUserSession(e,t){if(!this.redisClient||!e)return!1;try{let n=ij(this.redisConfig,e),o=await this.redisClient.sRem(n,t);return Number(o)>0}catch(n){return g.error("[RedisConversationMemoryManager] Failed to remove session from user set",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n)}),!1}}generateTimestamp(){return new Date().toISOString()}async storeToolExecution(e,t,n,o,s){g.debug("[RedisConversationMemoryManager] Storing tool execution temporarily",{sessionId:e,userId:t,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});try{let i=t||"randomUser",a=`${e}:${i}`,l={toolCalls:(n||[]).map(d=>({...d,timestamp:s})),toolResults:(o||[]).map(d=>({...d,timestamp:s})),timestamp:Date.now()},u=this.pendingToolExecutions.get(a);u&&(g.debug("[RedisConversationMemoryManager] Merging with existing pending tool data",{sessionId:e,existingToolCalls:u.toolCalls.length,existingToolResults:u.toolResults.length,newToolCalls:n?.length||0,newToolResults:o?.length||0}),l.toolCalls=[...u.toolCalls,...l.toolCalls],l.toolResults=[...u.toolResults,...l.toolResults]),this.pendingToolExecutions.set(a,l),g.debug("[RedisConversationMemoryManager] Tool execution stored temporarily",{sessionId:e,userId:i,pendingKey:a,totalToolCalls:l.toolCalls.length,totalToolResults:l.toolResults.length}),this.cleanupStalePendingData()}catch(i){g.error("[RedisConversationMemoryManager] Failed to store tool execution temporarily",{sessionId:e,error:i instanceof Error?i.message:String(i)})}}async storeConversationTurn(e){return g.debug("[RedisConversationMemoryManager] Storing conversation turn",{sessionId:e.sessionId,userId:e.userId}),await this.ensureInitialized(),WA.startActiveSpan("neurolink.memory.storeTurn",{kind:er.CLIENT,attributes:{"session.id":e.sessionId,...e.userId&&{"user.id":e.userId}}},async t=>{try{if(!this.redisClient)throw new Error("Redis client not initialized");let n=ml(this.redisConfig,e.sessionId,e.userId),o=await this.redisClient.get(n),s=fl(o),i=new Date().toISOString(),a=e.userId||"randomUser";if(s)s.updatedAt=i;else{let h=`${e.sessionId}:${a}`,y=Sm(async()=>{if(!this.titleGenerationInProgress.has(h)){this.titleGenerationInProgress.add(h);try{let v=await this.generateConversationTitle(e.userMessage),b=ml(this.redisConfig,e.sessionId,e.userId||void 0),S=await this.redisClient?.get(b),w=fl(S||null);if(w){w.title=v,w.updatedAt=new Date().toISOString();let _=zw(w);await this.redisClient?.set(b,_),this.redisConfig.ttl>0&&await this.redisClient?.expire(b,this.redisConfig.ttl)}}catch(v){g.warn("[RedisConversationMemoryManager] Failed to generate conversation title in background",{sessionId:e.sessionId,userId:a,error:v instanceof Error?v.message:String(v)})}finally{this.titleGenerationInProgress.delete(h)}}});setImmediate(y),s={id:Fe(),title:"New Conversation",sessionId:e.sessionId,userId:a,createdAt:e.startTimeStamp?.toISOString()||i,updatedAt:e.startTimeStamp?.toISOString()||i,messages:[]}}let l=e.providerDetails?nz(e.providerDetails.provider,e.providerDetails.model,this.config.tokenThreshold,s.tokenThreshold):this.config.tokenThreshold||5e4,u={id:Fe(),timestamp:e.startTimeStamp?.toISOString()||this.generateTimestamp(),role:"user",content:e.userMessage};s.messages.push(u),await this.flushPendingToolData(s,e.sessionId,a);let d={id:Fe(),timestamp:this.generateTimestamp(),role:"assistant",content:e.aiResponse,events:e.events||void 0,...e.thoughtSignature&&{metadata:{thoughtSignature:e.thoughtSignature}}};if(s.messages.push(d),e.tokenUsage&&(s.lastApiTokenCount=e.tokenUsage),g.info("[RedisConversationMemoryManager] Added new messages",{sessionId:s.sessionId,userId:s.userId}),e.enableSummarization!==void 0?e.enableSummarization:this.config.enableSummarization){let h=e.userId||"randomUser",y=`${e.sessionId}:${h}`;if(this.summarizationInProgress.has(y))g.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:e.sessionId,userId:h});else{let v=Sm(async()=>{try{await this.checkAndSummarize(s,l,e.sessionId,e.userId,e.requestId)}catch(b){g.error("Background summarization failed",{sessionId:s.sessionId,error:b instanceof Error?b.message:String(b)})}});setImmediate(v)}}let m=zw(s);await this.redisClient.set(n,m);let f=Buffer.byteLength(m,"utf8");g.info("[ConversationMemory] Turn stored",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:f,totalMessages:s.messages.length,userMsgChars:e.userMessage.length,assistantMsgChars:e.aiResponse.length}),f>512*1024&&g.warn("[ConversationMemory] Large session blob",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:f,messageCount:s.messages.length}),this.redisConfig.ttl>0&&await this.redisClient.expire(n,this.redisConfig.ttl),e.userId&&await this.addUserSession(e.userId,e.sessionId),t.setAttribute("message.count",s.messages.length),t.setStatus({code:be.OK}),g.debug("[RedisConversationMemoryManager] Successfully stored conversation turn",{sessionId:e.sessionId,totalMessages:s.messages.length,title:s.title})}catch(n){throw t.setStatus({code:be.ERROR,message:n instanceof Error?n.message:String(n)}),t.recordException(n instanceof Error?n:new Error(String(n))),new qi(`Failed to store conversation turn in Redis for session ${e.sessionId}`,"STORAGE_ERROR",{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n)})}finally{t.end()}})}async checkAndSummarize(e,t,n,o,s){let i=o||"randomUser",a=`${n}:${i}`;if(this.summarizationInProgress.has(a)){g.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:n,userId:i});return}this.summarizationInProgress.add(a);try{let l={sessionId:e.sessionId,userId:e.userId,messages:e.messages,summarizedUpToMessageId:e.summarizedUpToMessageId,summarizedMessage:e.summarizedMessage,tokenThreshold:e.tokenThreshold,lastTokenCount:e.lastTokenCount,lastCountedAt:e.lastCountedAt,createdAt:new Date(e.createdAt).getTime(),lastActivity:new Date(e.updatedAt).getTime()},u=await this.summarizationEngine.checkAndSummarize(l,t,this.config,"[RedisConversationMemoryManager]",s);if(e.lastTokenCount=l.lastTokenCount,e.lastCountedAt=l.lastCountedAt,u&&(e.summarizedUpToMessageId=l.summarizedUpToMessageId,e.summarizedMessage=l.summarizedMessage,this.redisClient)){let d=ml(this.redisConfig,n,o),p=await this.redisClient.get(d);if(p){let m=fl(p);if(m){m.summarizedUpToMessageId=e.summarizedUpToMessageId,m.summarizedMessage=e.summarizedMessage,m.lastTokenCount=e.lastTokenCount,m.lastCountedAt=e.lastCountedAt;let f=zw(m);await this.redisClient.set(d,f),this.redisConfig.ttl>0&&await this.redisClient.expire(d,this.redisConfig.ttl)}}}}catch(l){g.error("Token counting or summarization failed",{sessionId:e.sessionId,error:l instanceof Error?l.message:String(l)})}finally{this.summarizationInProgress.delete(a)}}async buildContextMessages(e,t,n,o){if(g.debug("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,enableSummarization:n}),await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available in buildContextMessages"),[];let s=this.redisClient;return WA.startActiveSpan("neurolink.memory.buildContext",{kind:er.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async i=>{try{g.info("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,method:"buildContextMessages"});let a=ml(this.redisConfig,e,t),l=await Oe(s.get(a),Ote),u=fl(l||null);if(g.debug("[RedisConversationMemoryManager] Retrieved conversation for context building",{sessionId:e,userId:t,conversationFound:!!u}),!u)return i.setAttribute("session.found",!1),i.setStatus({code:be.OK}),[];let d={sessionId:u.sessionId,userId:u.userId,messages:u.messages,summarizedUpToMessageId:u.summarizedUpToMessageId,summarizedMessage:u.summarizedMessage,tokenThreshold:u.tokenThreshold,lastTokenCount:u.lastTokenCount,lastCountedAt:u.lastCountedAt,createdAt:new Date(u.createdAt).getTime(),lastActivity:new Date(u.updatedAt).getTime()},p=GS(d,o);g.debug("[RedisConversationMemoryManager] Built context messages from pointer",{sessionId:e,userId:t,contextMessageCount:p.length,pointerMessageId:d.summarizedUpToMessageId||"none"});let m=this.config?.contextCompaction?.sendToolPreview===!0,f=p.map(h=>{if(h.role!=="tool_result")return h;let y=m&&h.metadata?.toolOutputPreview?h.metadata.toolOutputPreview:h.content,v=h.result;if(h.result&&h.result.result===void 0){let b=y;try{b=JSON.parse(y)}catch{}v={...h.result,result:b}}return g.debug("[RedisConversationMemoryManager] Processing tool_result message for context",{sessionId:e,userId:t,messageId:h.id,sendToolPreview:m,hasPreview:!!h.metadata?.toolOutputPreview,contentLength:y?String(y).length:0,resultHydrated:v!==h.result}),{...h,content:y,result:v}});return i.setAttribute("context.message_count",f.length),i.setStatus({code:be.OK}),g.info("[RedisConversationMemoryManager] Retrieved context messages",{sessionId:e,userId:t}),f}catch(a){throw i.setStatus({code:be.ERROR,message:a instanceof Error?a.message:String(a)}),i.recordException(a instanceof Error?a:new Error(String(a))),a}finally{i.end()}})}async getUserSessionMetadata(e,t){if(g.debug("[RedisConversationMemoryManager] Getting user session metadata",{userId:e,sessionId:t}),await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e,sessionId:t}),null;try{let n=ml(this.redisConfig,t,e),o=await this.redisClient.get(n);if(!o)return g.debug("[RedisConversationMemoryManager] No session data found",{userId:e,sessionId:t,sessionKey:n}),null;let s=fl(o);return s?{id:s.sessionId,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt,metadata:s.additionalMetadata?.agenticLoopReports?{agenticLoopReports:s.additionalMetadata.agenticLoopReports}:void 0}:(g.debug("[RedisConversationMemoryManager] No valid conversation data found",{userId:e,sessionId:t,sessionKey:n}),null)}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get user session metadata",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0}),null}}async getUserSessionHistory(e,t){g.debug("[RedisConversationMemoryManager] Getting user session history via getUserSessionObject",{userId:e,sessionId:t});try{let n=await this.getUserSessionObject(e,t);return n?n.messages:(g.debug("[RedisConversationMemoryManager] No session object found, returning null",{userId:e,sessionId:t}),null)}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get user session history via getUserSessionObject",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n),errorName:n instanceof Error?n.name:"UnknownError",stack:n instanceof Error?n.stack:void 0}),null}}async getUserSessionObject(e,t){if(g.debug("[RedisConversationMemoryManager] Getting complete user session object",{userId:e,sessionId:t,method:"getUserSessionObject"}),!e||typeof e!="string")return g.warn("[RedisConversationMemoryManager] Invalid userId provided",{userId:e,sessionId:t}),null;if(!t||typeof t!="string")return g.warn("[RedisConversationMemoryManager] Invalid sessionId provided",{userId:e,sessionId:t}),null;if(await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available for getUserSessionObject",{userId:e,sessionId:t}),null;try{let n=ml(this.redisConfig,t,e),o=await this.redisClient.get(n);if(!o)return g.debug("[RedisConversationMemoryManager] No conversation data found in Redis",{userId:e,sessionId:t,sessionKey:n}),null;let s=fl(o);return s?!s.messages||!Array.isArray(s.messages)?(g.warn("[RedisConversationMemoryManager] Invalid conversation structure - missing messages array",{userId:e,sessionId:t,hasMessages:!!s.messages,messagesType:typeof s.messages}),null):s:(g.debug("[RedisConversationMemoryManager] Failed to deserialize conversation data",{userId:e,sessionId:t,sessionKey:n,dataLength:o.length}),null)}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get complete user session object",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n),errorName:n instanceof Error?n.name:"UnknownError",stack:n instanceof Error?n.stack:void 0}),null}}async generateConversationTitle(e){g.info("[RedisConversationMemoryManager] Generating conversation title",{userMessageLength:e.length,userMessagePreview:e.substring(0,100)});try{let t=new Fv({conversationMemory:{enabled:!1}}),n=`Generate a clear, concise, and descriptive title (5\u20138 words maximum) for a conversation based on the following user message.
|
|
2167
|
+
pnpm add pptxgenjs`,{cause:r}):r}}var ZB,XB,nte=A(async()=>{"use strict";aR();dn();vr();Ov();Q();bt();bo();I1e();ZB=null;XB=class{theme;config;neurolink;imageLimit;userImageIndex=0;constructor(e){this.config=e,this.theme=typeof e.theme=="string"?zee(e.theme):e.theme,this.neurolink=e.neurolink||null,this.imageLimit=op(Wee)}getNextUserImage(){let e=this.config.userImages;if(!e||e.length===0)return;let t=e[this.userImageIndex%e.length];return this.userImageIndex++,t}async loadUserImage(e){try{if(Buffer.isBuffer(e))return e;if(e.startsWith("http://")||e.startsWith("https://")){let o=await Oe(fetch(e),15e3,pe.toolTimeout("userImageFetch",15e3));if(!o.ok){g.warn(`[SlideGenerator] Failed to fetch user image: ${e}`);return}return Buffer.from(await o.arrayBuffer())}return await(await Promise.resolve().then(()=>(Pu(),$f))).readFile(e)}catch(n){g.warn("[SlideGenerator] Failed to load user image",{error:n instanceof Error?n.message:String(n)});return}}async generateSlide(e){let t=xe.createSpan("ppt.generation","ppt.generateSlide",{"ppt.operation":"generateSlide","ppt.slideIndex":e.slideNumber,"ppt.theme":this.theme.name}),n=Date.now();try{let o,s;if(zA(e.type)){let l=this.getNextUserImage();if(l&&(g.info(`[SlideGenerator] \u{1F4F7} Using user-provided image for slide ${e.slideNumber}: "${e.title}"`),o=await this.loadUserImage(l),o&&(s={prompt:"User-provided image",model:"user-upload",generatedAt:new Date})),!o&&this.config.generateAIImages&&e.imagePrompt){g.info(`[SlideGenerator] \u23F3 Generating AI image for slide ${e.slideNumber}: "${e.title}"...`);let u=await this.generateImage(e.imagePrompt,e.type);u&&(o=u.buffer,s={prompt:e.imagePrompt,model:u.model,generatedAt:new Date})}}let i=Date.now()-n;g.debug(`[SlideGenerator] Generated slide ${e.slideNumber} (${e.type})`,{hasImage:!!o,generationTime:i});let a=xe.endSpan(t,1);return Ue().recordSpan(a),{slideNumber:e.slideNumber,schema:e,imageBuffer:o,imageMetadata:s,generationTime:i}}catch(o){let s=xe.endSpan(t,2);s.statusMessage=o instanceof Error?o.message:String(o),Ue().recordSpan(s);let i=o instanceof Je?o:pe.toolExecutionFailed("slideGenerator",o instanceof Error?o:new Error(String(o)));return g.error(`[SlideGenerator] Failed to generate slide ${e.slideNumber}`,{error:i.message,type:e.type}),{slideNumber:e.slideNumber,schema:e,generationTime:Date.now()-n}}}async generateSlides(e){let t=Date.now(),n=this.config.generateAIImages?e.filter(d=>d.imagePrompt&&zA(d.type)).length:0,o=this.config.userImages?.length??0;g.info(`[SlideGenerator] Generating ${e.length} slides...`,{theme:this.theme.name,generateAIImages:this.config.generateAIImages,slidesNeedingAIImages:n,userImagesProvided:o}),this.userImageIndex=0;let s=e.map(d=>this.imageLimit(()=>this.generateSlide(d))),i=await Promise.all(s),a=i.filter(d=>d.imageBuffer).length,l=this.config.generateAIImages?e.filter(d=>d.imagePrompt&&zA(d.type)&&!i.find(p=>p.slideNumber===d.slideNumber)?.imageBuffer).length:0,u=Date.now()-t;return g.info("[SlideGenerator] Slide generation complete",{totalSlides:i.length,totalImages:a,failedImages:l,generationTime:u}),{slides:i,totalImages:a,failedImages:l,generationTime:u}}renderSlide(e,t,n,o){let{schema:s,imageBuffer:i}=t,a=e.addSlide();return this.applyBackground(a,s.type),this.applyLayout(a,s,i),s.type!=="title"&&s.type!=="thank-you"&&this.addSlideNumber(a,n,o),this.addLogo(a,s.type),s.speakerNotes&&a.addNotes(s.speakerNotes),a}async generateImage(e,t){if(!this.neurolink)return g.warn("[SlideGenerator] No NeuroLink instance provided, skipping image generation"),null;try{let n=qee(e,this.theme.name);g.debug(`[SlideGenerator] Generating image for ${t}`,{promptPreview:n.substring(0,100)});let o=await Oe(this.neurolink.generate({input:{text:n},provider:this.config.provider||"vertex",model:this.config.imageModel||"gemini-2.5-flash-image"}),VB,pe.toolTimeout("imageGeneration",VB));if(!o||!o.imageOutput?.base64)return g.warn(`[SlideGenerator] No image data returned for ${t}`),null;let s=Buffer.from(o.imageOutput.base64,"base64");return s.length<100?(g.warn(`[SlideGenerator] Image buffer too small (${s.length} bytes) for ${t}`),null):(s[0]===255&&s[1]===216&&s[2]===255||s[0]===137&&s[1]===80&&s[2]===78&&s[3]===71||s[0]===71&&s[1]===73&&s[2]===70||s[0]===82&&s[1]===73&&s[2]===70&&s[3]===70||g.warn(`[SlideGenerator] Unknown image format for ${t}, magic bytes: ${s.slice(0,4).toString("hex")}`),g.debug(`[SlideGenerator] Image generated successfully for ${t}`,{size:s.length,format:s[0]===255?"JPEG":s[0]===137?"PNG":s[0]===71?"GIF":"unknown"}),{buffer:s,model:o.model||this.config.imageModel})}catch(n){let o=n instanceof Je?n:pe.toolExecutionFailed("imageGeneration",n instanceof Error?n:new Error(String(n)));return g.error("[SlideGenerator] Image generation failed",{error:o.message,slideType:t}),null}}applyBackground(e,t){e.background={color:this.theme.colors.background.replace("#","")}}applyLayout(e,t,n){let{type:o,layout:s,title:i,content:a}=t;switch(o){case"title":i1e(e,i,a,this.theme,n);break;case"section-header":a1e(e,i,a,this.theme);break;case"content":case"bullets":case"agenda":case"numbered-list":JB({slide:e,title:i,content:a,layout:s,theme:this.theme,imageBuffer:n,slideType:o});break;case"image-focus":case"image-left":case"image-right":case"full-bleed-image":l1e(e,i,a,s,this.theme,n);break;case"two-column":case"split-content":d1e(e,i,a,s,this.theme,n);break;case"three-column":p1e(e,i,a,this.theme);break;case"quote":m1e(e,i,a,this.theme);break;case"statistics":f1e(e,i,a,this.theme);break;case"chart-bar":case"chart-line":case"chart-pie":case"chart-area":g1e(e,i,a,o,this.theme);break;case"table":h1e(e,i,a,this.theme);break;case"timeline":y1e(e,i,a,this.theme);break;case"process-flow":v1e(e,i,a,this.theme);break;case"comparison":x1e(e,i,a,this.theme);break;case"features":case"icons":b1e(e,i,a,this.theme);break;case"team":T1e(e,i,a,this.theme);break;case"conclusion":S1e(e,i,a,this.theme);break;case"thank-you":case"closing":c1e(e,i,a,this.theme,n);break;case"dashboard":a.dashboard&&C1e(e,i,a.dashboard,this.theme);break;case"mixed-content":k1e(e,i,a,this.theme);break;case"stats-grid":R1e(e,i,a,this.theme);break;case"icon-grid":A1e(e,i,a,this.theme);break;case"blank":break;default:JB({slide:e,title:i,content:a,layout:s,theme:this.theme,imageBuffer:n,slideType:o})}}getLogoConfig(){return this.config.logo?Buffer.isBuffer(this.config.logo)||typeof this.config.logo=="string"?{data:this.config.logo,position:"bottom-right",width:1,height:.4,showOn:"all-slides"}:{data:this.config.logo.data,position:this.config.logo.position||"bottom-right",width:this.config.logo.width||1,height:this.config.logo.height||.4,showOn:this.config.logo.showOn||"all-slides"}:null}getLogoDataUri(e){if(Buffer.isBuffer(e))return`data:image/png;base64,${e.toString("base64")}`;if(e.startsWith("data:"))return e;if(e.includes("/")||e.includes("\\")||e.endsWith(".png")||e.endsWith(".jpg")||e.endsWith(".jpeg")||e.endsWith(".svg"))try{if(un(e)){let t=Ga(e),n=e.split(".").pop()?.toLowerCase();return`data:${n==="svg"?"image/svg+xml":n==="jpg"||n==="jpeg"?"image/jpeg":"image/png"};base64,${t.toString("base64")}`}}catch{g.warn("[SlideGenerator] Could not read logo file, treating as base64")}return`data:image/png;base64,${e}`}addLogo(e,t){let n=this.getLogoConfig();if(!n)return;let o=n.showOn||"all-slides";if(o==="title-only"&&t!=="title"||o==="title-and-closing"&&t!=="title"&&t!=="thank-you"&&t!=="closing")return;let s=this.getLogoDataUri(n.data),i=n.position||"bottom-right",a=n.width||1,l=n.height||.4,u,d,p=Nt.logo;if(i==="title-only"?(u=p["bottom-right"].x,d=p["bottom-right"].y):(u=p[i].x,d=p[i].y),i==="top-right"||i==="bottom-right"){let{width:m}=IW[this.config.aspectRatio];u=m-a-.3}if(i==="bottom-left"||i==="bottom-right"){let{height:m}=IW[this.config.aspectRatio];d=m-l-.2}e.addImage({data:s,x:u,y:d,w:a,h:l,sizing:{type:"contain",w:a,h:l}})}addSlideNumber(e,t,n){e.addText(`${t} / ${n}`,{x:Nt.footer.x,y:Nt.footer.y,w:Nt.footer.w,h:Nt.footer.h,fontSize:this.theme.fonts.sizes.caption,fontFace:this.theme.fonts.body,color:this.theme.colors.muted.replace("#",""),align:"right"})}}});function Her(r){let e=r.trim();for(let{patterns:t,slideType:n,bulletStyle:o}of Ger)for(let s of t)if(s.test(e))return{slideType:n,bulletStyle:o};return{slideType:null,bulletStyle:null}}function Ker(r){if(!r||r.length===0)return null;for(let e of r)for(let{pattern:t,bulletStyle:n}of Wer)if(t.test(e.text))return n;return null}function N1e(r){switch(r){case"agenda":case"numbered-list":return"number";case"conclusion":case"closing":case"thank-you":return"checkmark";case"comparison":return"arrow";case"features":case"icons":case"quote":case"statistics":case"title":case"section-header":return"none";default:return"disc"}}function D1e(r,e,t){let{slideType:n,bulletStyle:o}=Her(r);if(n)return{type:n,bulletStyle:o||N1e(n),wasInferred:!0};let s=t.bullets?Ker(t.bullets):null;return s?{type:e,bulletStyle:s,wasInferred:!0}:{type:e,bulletStyle:N1e(e),wasInferred:!1}}function L1e(r,e){return(r.bullets?.length??0)>0||(r.leftColumn?.bullets?.length??0)>0||(r.rightColumn?.bullets?.length??0)>0||(r.centerColumn?.bullets?.length??0)>0?{...r,bullets:r.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||e})),leftColumn:r.leftColumn?{...r.leftColumn,bullets:r.leftColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||e}))}:void 0,rightColumn:r.rightColumn?{...r.rightColumn,bullets:r.rightColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||e}))}:void 0,centerColumn:r.centerColumn?{...r.centerColumn,bullets:r.centerColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||e}))}:void 0}:r}var Ger,Wer,F1e=A(()=>{"use strict";Ger=[{patterns:[/\bagenda\b/i,/\btable\s+of\s+contents\b/i,/\boutline\b/i,/\boverview\b/i,/\bwhat\s+we('ll)?\s+cover\b/i,/\btoday('s)?\s+topics?\b/i,/\bsession\s+outline\b/i],slideType:"agenda",bulletStyle:"number"},{patterns:[/\bconclusion\b/i,/\bsummary\b/i,/\bkey\s+takeaways?\b/i,/\btakeaways?\b/i,/\brecap\b/i,/\bin\s+summary\b/i,/\bwhat\s+we('ve)?\s+learned\b/i,/\bmain\s+points?\b/i,/\bkey\s+points?\b/i,/\bhighlights?\b/i,/\bachievements?\b/i,/\baccomplishments?\b/i],slideType:"conclusion",bulletStyle:"checkmark"},{patterns:[/\bthank\s+you\b/i,/\bthanks?\b/i,/\bquestions?\b\??/i,/\bq\s*&\s*a\b/i,/\bcontact(\s+us)?\b/i,/\bnext\s+steps?\b/i,/\baction\s+items?\b/i,/\blet('s)?\s+connect\b/i,/\bget\s+(in\s+)?touch\b/i],slideType:"closing",bulletStyle:"checkmark"},{patterns:[/\bcomparison\b/i,/\bcompare\b/i,/\bvs\.?\b/i,/\bversus\b/i,/\bbefore\s+(and|&|vs\.?)\s+after\b/i,/\bpros?\s+(and|&|vs\.?)\s+cons?\b/i,/\badvantages?\s+(and|&|vs\.?)\s+disadvantages?\b/i,/\bbenefits?\s+(and|&|vs\.?)\s+risks?\b/i,/\bold\s+vs\.?\s+new\b/i],slideType:"comparison",bulletStyle:"arrow"},{patterns:[/\bprocess\b/i,/\bsteps?\b/i,/\bstep[\s-]+by[\s-]+step\b/i,/\bhow\s+to\b/i,/\bworkflow\b/i,/\bprocedure\b/i,/\bmethodology\b/i,/\d+\s+steps?\s+to\b/i,/\bimplementation\s+steps?\b/i,/\bgetting\s+started\b/i],slideType:"numbered-list",bulletStyle:"number"},{patterns:[/\bfeatures?\b/i,/\bcapabilities?\b/i,/\bwhat\s+(we|it)\s+offers?\b/i,/\bour\s+offerings?\b/i],slideType:"features",bulletStyle:"disc"},{patterns:[/\bbenefits?\b/i,/\badvantages?\b/i,/\bwhy\s+choose\b/i,/\breasons?\s+to\b/i,/\bvalue\s+proposition\b/i],slideType:"content",bulletStyle:"checkmark"},{patterns:[/\bgoals?\b/i,/\bobjectives?\b/i,/\btargets?\b/i,/\baims?\b/i,/\bour\s+mission\b/i,/\bwhat\s+we\s+aim\s+for\b/i],slideType:"content",bulletStyle:"checkmark"},{patterns:[/\bchallenges?\b/i,/\brisks?\b/i,/\bobstacles?\b/i,/\bbarriers?\b/i,/\bconcerns?\b/i,/\bissues?\b/i,/\bproblems?\b/i],slideType:"content",bulletStyle:"arrow"},{patterns:[/\brequirements?\b/i,/\bchecklist\b/i,/\bprerequisites?\b/i,/\bwhat\s+you\s+need\b/i,/\bmust\s+haves?\b/i,/\bessentials?\b/i],slideType:"content",bulletStyle:"checkmark"}];Wer=[{pattern:/^\d+[.)]\s+/m,bulletStyle:"number"},{pattern:/^step\s+\d+/im,bulletStyle:"number"},{pattern:/^[✓✔☑]\s*/m,bulletStyle:"checkmark"},{pattern:/^\[x\]\s*/im,bulletStyle:"checkmark"},{pattern:/^done:/im,bulletStyle:"checkmark"},{pattern:/^completed:/im,bulletStyle:"checkmark"},{pattern:/^[→➜➡]\s*/m,bulletStyle:"arrow"},{pattern:/^->\s*/m,bulletStyle:"arrow"},{pattern:/^=>\s*/m,bulletStyle:"arrow"}]});function Xer(r,e="content"){return typeof r=="string"&&Jer.has(r)?r:(g.warn(`[ContentPlanner] Invalid slide type "${r}", using "${e}"`),e)}function Yer(r,e){if(typeof r=="string"&&Zer.has(r))return r;let n=qB[e]?.[0]||"title-content";return g.warn(`[ContentPlanner] Invalid layout "${r}" for type "${e}", using "${n}"`),n}function etr(r){if(r&&typeof r=="object"&&"text"in r){let e=r,t={text:String(e.text||"")};return Array.isArray(e.subBullets)&&(t.subBullets=e.subBullets.map(n=>String(n))),typeof e.icon=="string"&&(t.icon=e.icon),typeof e.emphasis=="boolean"&&(t.emphasis=e.emphasis),typeof e.fontSize=="number"&&e.fontSize>=8&&e.fontSize<=48&&(t.fontSize=e.fontSize),typeof e.bulletStyle=="string"&&Qer.has(e.bulletStyle)&&(t.bulletStyle=e.bulletStyle),typeof e.color=="string"&&e.color.match(/^#?[0-9A-Fa-f]{6}$/)&&(t.color=e.color.startsWith("#")?e.color:`#${e.color}`),typeof e.bold=="boolean"&&(t.bold=e.bold),t.text?t:null}return typeof r=="string"&&r.trim()?{text:r.trim()}:null}function YB(r){if(!Array.isArray(r))return[];let e=[];for(let t of r){let n=etr(t);n&&e.push(n)}return e}function ttr(r){if(!r||typeof r!="object")return{};let e=r,t={};if(e.bullets&&(t.bullets=YB(e.bullets)),e.leftColumn&&typeof e.leftColumn=="object"){let o=e.leftColumn;t.leftColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?YB(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(e.rightColumn&&typeof e.rightColumn=="object"){let o=e.rightColumn;t.rightColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?YB(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(e.centerColumn&&typeof e.centerColumn=="object"){let o=e.centerColumn;t.centerColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?YB(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}let n=["subtitle","body","sectionNumber","quote","quoteAuthor","quoteAuthorTitle","caption","galleryImages","statistics","chartData","tableData","timeline","processSteps","features","icons","teamMembers","comparison","nextSteps","cta","ctaButton","contactInfo","layoutOptions","dashboard"];for(let o of n)e[o]!==void 0&&(t[o]=e[o]);return t}function rtr(r,e){if(!r||typeof r!="object")throw new ki("AI returned invalid response: expected object",pl.INVALID_AI_RESPONSE,{received:typeof r});let t=r;if(typeof t.title!="string"||!t.title.trim())throw new ki("AI response missing valid 'title' field",pl.INVALID_AI_RESPONSE,{field:"title",received:t.title});if(!Array.isArray(t.slides))throw new ki("AI response missing 'slides' array",pl.INVALID_AI_RESPONSE,{field:"slides",received:typeof t.slides});t.slides.length!==e&&g.warn(`[ContentPlanner] AI returned ${t.slides.length} slides, expected ${e}. Adjusting...`);let n=[];for(let o=0;o<t.slides.length;o++){let s=t.slides[o];if(!s||typeof s!="object")throw new ki(`Invalid slide at index ${o}`,pl.INVALID_AI_RESPONSE,{index:o,received:typeof s});typeof s.title!="string"&&(s.title=`Slide ${o+1}`,g.warn(`[ContentPlanner] Slide ${o+1} missing title, using default`));let i=Xer(s.type,"content"),a=ttr(s.content),{type:l,bulletStyle:u,wasInferred:d}=D1e(s.title,i,a),p=d&&l!==i?l:i;d&&l!==i&&g.debug(`[ContentPlanner] Slide ${o+1} type inferred from title: "${s.title}" \u2192 ${p}`);let m=L1e(a,u),f=Yer(s.layout,p);typeof s.speakerNotes!="string"&&(s.speakerNotes=""),s.imagePrompt!==null&&typeof s.imagePrompt!="string"&&(s.imagePrompt=null),n.push({slideNumber:o+1,type:p,layout:f,title:s.title,content:m,imagePrompt:s.imagePrompt,speakerNotes:s.speakerNotes})}return{title:t.title,totalSlides:n.length,audience:t.audience||"general",tone:t.tone||"professional",theme:t.theme||"modern",slides:n,keyMessages:Array.isArray(t.keyMessages)?t.keyMessages:void 0}}function ntr(r){let e=r.trim();e.startsWith("```")&&(e=e.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""));try{return JSON.parse(e)}catch(t){throw new ki(`Failed to parse AI response as JSON: ${t instanceof Error?t.message:String(t)}`,pl.INVALID_AI_RESPONSE,{contentPreview:r.substring(0,500),parseError:t instanceof Error?t.message:String(t)})}}async function U1e(r,e){let t=Date.now(),n=`session-${Date.now()}`;g.info("[ContentPlanner] Starting content planning",{topic:r.topic.substring(0,100),pages:r.pages,audience:r.audience,tone:r.tone,theme:r.theme,generateAIImages:r.generateAIImages,provider:r.provider,model:r.model,sessionId:n});let o=jee({topic:r.topic,pages:r.pages,audience:r.audience,tone:r.tone,theme:r.theme,generateAIImages:r.generateAIImages,modelInfo:{name:r.model||"unknown",provider:r.provider||"auto-selected"}});try{let s=await e.generate({prompt:o,systemPrompt:Bee,temperature:.7,maxTokens:8192,disableTools:!0,timeout:Hee});if(!s||!s.content)throw new ki("AI provider returned empty response",pl.PLANNING_FAILED,{provider:r.provider});let i=Date.now()-t;g.debug("[ContentPlanner] AI response received",{contentLength:s.content.length,planningTime:i});let a=ntr(s.content),l=rtr(a,r.pages);return g.info("[ContentPlanner] Content plan generated successfully",{title:l.title,totalSlides:l.totalSlides,planningTime:i,keyMessages:l.keyMessages?.length||0}),l}catch(s){if(s instanceof ki)throw s;let i=s instanceof Error?s.message:String(s);throw new ki(`Content planning failed: ${i}`,pl.PLANNING_FAILED,{topic:r.topic.substring(0,100),provider:r.provider},s instanceof Error?s:void 0)}}function otr(r){return r.slides.length>0&&r.slides[0].type!=="title"&&(r.slides[0]={...r.slides[0],type:"title",layout:"title-centered"}),r}function str(r){let e=r.slides.length-1;return e>=0&&r.slides[e].type!=="thank-you"&&(r.slides[e]={...r.slides[e],type:"thank-you",layout:"contact-info"}),r}function $1e(r){let e={...r,slides:[...r.slides]};return e=otr(e),e=str(e),e}var Jer,Zer,Qer,z1e=A(()=>{"use strict";GB();Ov();F1e();Q();Jer=new Set(["title","section-header","thank-you","closing","content","agenda","bullets","numbered-list","image-focus","image-left","image-right","full-bleed-image","gallery","two-column","three-column","split-content","table","chart-bar","chart-line","chart-pie","chart-area","statistics","quote","timeline","process-flow","comparison","features","team","icons","conclusion","blank","dashboard","mixed-content","stats-grid","icon-grid"]),Zer=new Set(["title-centered","title-bottom","title-left-aligned","title-content","title-content-footer","content-only","image-left-content-right","image-right-content-left","image-top-content-bottom","image-bottom-content-top","image-full-overlay","image-centered","image-grid-2x2","two-column-equal","two-column-wide-left","two-column-wide-right","three-column-equal","chart-full","chart-with-bullets","table-full","table-with-notes","quote-centered","quote-with-image","statistics-row","statistics-grid","timeline-horizontal","timeline-vertical","process-horizontal","process-vertical","comparison-side-by-side","comparison-table","team-grid","icon-grid","summary-bullets","contact-info","blank-full"]);Qer=new Set(["disc","number","checkmark","arrow","dash","none"])});var B1e={};le(B1e,{generatePresentation:()=>itr});async function itr(r){let e=xe.createSpan("ppt.generation","ppt.orchestrate",{"ppt.operation":"orchestrate","ppt.slideCount":r.context.pages,"ppt.theme":typeof r.context.theme=="string"?r.context.theme:"custom"}),t={startTime:Date.now(),contentPlan:null,slides:null,outputPath:null},{context:n,provider:o,providerName:s,modelName:i,neurolink:a,imageProvider:l,imageModel:u}=r;g.info("[PresentationOrchestrator] Starting presentation generation",{topic:n.topic.substring(0,100),pages:n.pages,theme:n.theme,audience:n.audience,tone:n.tone,generateAIImages:n.generateAIImages,provider:n.provider});try{g.info("[PresentationOrchestrator] Step 1: Content planning...");let d=await Oe(U1e(n,o),Kl/2,pe.toolTimeout("contentPlanning",Kl/2));t.contentPlan=$1e(d),e.attributes["ppt.slideCount"]=t.contentPlan.totalSlides,e.attributes["ppt.theme"]=typeof t.contentPlan.theme=="string"?t.contentPlan.theme:"custom",g.info("[PresentationOrchestrator] Content plan ready",{title:t.contentPlan.title,totalSlides:t.contentPlan.totalSlides,theme:t.contentPlan.theme,audience:t.contentPlan.audience,tone:t.contentPlan.tone}),g.info("[PresentationOrchestrator] Step 2: Generating slides...");let p=n.logo??null,m=Xee(p),h={theme:t.contentPlan.theme||n.theme,generateAIImages:n.generateAIImages,aspectRatio:n.aspectRatio,provider:l??n.provider??"vertex",imageModel:u??"gemini-2.5-flash-image",logo:m??void 0,userImages:n.images,neurolink:a},y=new XB(h),v=await Oe(y.generateSlides(t.contentPlan.slides),Kl/2,pe.toolTimeout("slideGeneration",Kl/2));t.slides=v.slides,g.info("[PresentationOrchestrator] Slides generated",{totalSlides:t.slides.length,totalImages:v.totalImages,failedImages:v.failedImages,generationTime:v.generationTime}),g.info("[PresentationOrchestrator] Step 3: Assembling PPTX...");let b=await O1e(),S=new b;S.title=t.contentPlan.title,S.subject=`Generated presentation about: ${n.topic.substring(0,100)}`,S.author="NeuroLink PPT Generator",S.company="NeuroLink",S.layout=Yee(n.aspectRatio);let w=[...t.slides].sort((M,N)=>M.slideNumber-N.slideNumber);for(let M=0;M<w.length;M++){let N=w[M];y.renderSlide(S,N,M+1,w.length)}g.info("[PresentationOrchestrator] PPTX assembled",{totalSlides:w.length,layout:S.layout,title:S.title}),g.info("[PresentationOrchestrator] Step 4: Writing file..."),t.outputPath=Jee(n),await Oe(Zee(t.outputPath),Kl/4,pe.toolTimeout("outputDirectory",Kl/4)),await Oe(S.writeFile({fileName:t.outputPath}),Kl/4,pe.toolTimeout("pptxWrite",Kl/4));let _=0;try{_=(await Oe(Lk(t.outputPath),Kl/8,pe.toolTimeout("pptxStat",Kl/8))).size}catch{g.warn("[PresentationOrchestrator] Could not get file size")}let C=Date.now()-t.startTime;g.info("[PresentationOrchestrator] Presentation generation complete",{filePath:t.outputPath,fileSize:_,totalSlides:w.length,totalTime:C});let R=xe.endSpan(e,1);Ue().recordSpan(R),a?.recordMetricsSpan(R);let I=t.contentPlan?.theme||n.theme,k=t.contentPlan?.audience||n.audience,E=t.contentPlan?.tone||n.tone;return{filePath:t.outputPath,totalSlides:w.length,format:"pptx",provider:s,model:i,metadata:{theme:I,audience:k,tone:E,imageModel:n.generateAIImages?u??"gemini-2.5-flash-image":"",fileSize:_>0?_:0}}}catch(d){let p=xe.endSpan(e,2);if(p.statusMessage=d instanceof Error?d.message:String(d),Ue().recordSpan(p),a?.recordMetricsSpan(p),d instanceof ki)throw g.error("[PresentationOrchestrator] Generation failed",{error:d.message,code:d.code,context:d.context}),d;let m=Qee(d);throw g.error("[PresentationOrchestrator] Unexpected error",{error:m.message,stage:HB(t)}),new ki(`Presentation generation failed: ${m.message}`,pl.ASSEMBLY_FAILED,{topic:n.topic.substring(0,100),stage:HB(t),elapsedTime:Date.now()-t.startTime},m)}}var j1e=A(async()=>{"use strict";await nte();Pu();GB();z1e();await nte();Ov();Q();bt();bo();KB()});var vp,Lw,QB=A(()=>{"use strict";xs();dr();Q();vp=class extends _r{config;pendingRequests=new Map;constructor(e={}){super(),this.config={defaultTimeout:e.defaultTimeout??6e4,enabled:e.enabled??!0,handler:e.handler??this.defaultHandler.bind(this),fallbackBehavior:e.fallbackBehavior??"timeout"}}setHandler(e){this.config.handler=e}setEnabled(e){if(this.config.enabled=e,!e)for(let[t,n]of this.pendingRequests)n.settled||(n.settled=!0,this.handleDisabled(n.request,n.resolve),n.timer&&clearTimeout(n.timer),this.pendingRequests.delete(t))}isEnabled(){return this.config.enabled}async request(e){let t={...e,id:e.id??Fe()};if(!this.config.enabled)return this.handleDisabledRequest(t);let n=t.timeout??this.config.defaultTimeout;return new Promise(o=>{let s=setTimeout(()=>{let i=this.pendingRequests.get(t.id);!i||i.settled||(i.settled=!0,this.handleTimeout(t,o))},n);this.pendingRequests.set(t.id,{request:t,resolve:o,timer:s,settled:!1}),this.emit("elicitationRequested",t),Promise.resolve().then(()=>this.config.handler(t)).then(i=>{let a=this.pendingRequests.get(t.id);!a||a.settled||(a.settled=!0,clearTimeout(s),this.pendingRequests.delete(t.id),this.emit("elicitationResponded",i),o(i))}).catch(i=>{let a=this.pendingRequests.get(t.id);if(!a||a.settled)return;a.settled=!0,clearTimeout(s),this.pendingRequests.delete(t.id);let l={requestId:t.id,responded:!1,error:i instanceof Error?i.message:String(i),timestamp:Date.now()};this.emit("elicitationError",{request:t,error:i}),o(l)})})}async confirm(e,t){let n={type:"confirmation",message:e,toolName:t?.toolName??"unknown",serverId:t?.serverId,confirmLabel:t?.confirmLabel,cancelLabel:t?.cancelLabel,timeout:t?.timeout};return(await this.request(n)).value===!0}async getText(e,t){let n={type:"text",message:e,toolName:t?.toolName??"unknown",placeholder:t?.placeholder,defaultValue:t?.defaultValue,timeout:t?.timeout};return(await this.request(n)).value}async select(e,t,n){let o={type:"select",message:e,toolName:n?.toolName??"unknown",options:t,timeout:n?.timeout};return(await this.request(o)).value}async multiSelect(e,t,n){let o={type:"multiselect",message:e,toolName:n?.toolName??"unknown",options:t,timeout:n?.timeout,minSelections:n?.minSelections,maxSelections:n?.maxSelections};return(await this.request(o)).value}async form(e,t,n){let o={type:"form",message:e,toolName:n?.toolName??"unknown",serverId:n?.serverId,fields:t,submitLabel:n?.submitLabel,timeout:n?.timeout};return(await this.request(o)).value}async getSecret(e,t){let n={type:"secret",message:e,toolName:t?.toolName??"unknown",hint:t?.hint,timeout:t?.timeout};return(await this.request(n)).value}cancel(e,t){let n=this.pendingRequests.get(e);if(n){if(n.settled)return;n.settled=!0,n.timer&&clearTimeout(n.timer);let o={requestId:e,responded:!1,cancelled:!0,error:t,timestamp:Date.now()};n.resolve(o),this.pendingRequests.delete(e),this.emit("elicitationCancelled",{requestId:e,reason:t})}}async defaultHandler(e){return g.warn(`[ElicitationManager] No handler for elicitation request: ${e.id}`),e.defaultValue!==void 0?{requestId:e.id,responded:!0,value:e.defaultValue,timestamp:Date.now()}:{requestId:e.id,responded:!1,error:"No elicitation handler configured",timestamp:Date.now()}}handleTimeout(e,t){this.pendingRequests.delete(e.id);let n={requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()};this.emit("elicitationTimeout",{request:e}),t(n)}handleDisabled(e,t){t(this.handleDisabledRequest(e))}handleDisabledRequest(e){switch(this.config.fallbackBehavior){case"default":return{requestId:e.id,responded:e.defaultValue!==void 0,value:e.defaultValue,timestamp:Date.now()};case"error":return{requestId:e.id,responded:!1,error:"Elicitation is disabled",timestamp:Date.now()};default:return{requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()}}}getPendingCount(){return this.pendingRequests.size}getPendingRequests(){return Array.from(this.pendingRequests.values()).map(e=>e.request)}clearPending(e){for(let[t]of this.pendingRequests)this.cancel(t,e??"Cleared")}},Lw=new vp});var q1e={};le(q1e,{ElicitationManager:()=>vp,globalElicitationManager:()=>Lw});var ote=A(()=>{"use strict";QB()});var V1e={};le(V1e,{MCPRegistryClient:()=>Fw,getAllWellKnownServers:()=>ate,getWellKnownServer:()=>ite,globalMCPRegistryClient:()=>ste});function ite(r){return ej.find(e=>e.id===r)}function ate(){return[...ej]}var ej,Fw,ste,cte=A(()=>{"use strict";xs();ej=[{id:"filesystem",name:"Filesystem",description:"File system operations - read, write, create, list directories",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-filesystem",command:"npx",args:["-y","@modelcontextprotocol/server-filesystem"],transports:["stdio"],categories:["file-system"],tags:["files","directories","read","write"],tools:["read_file","write_file","list_directory","create_directory"],verified:!0},{id:"github",name:"GitHub",description:"GitHub repository management and file operations",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-github",command:"npx",args:["-y","@modelcontextprotocol/server-github"],requiredEnvVars:["GITHUB_PERSONAL_ACCESS_TOKEN"],transports:["stdio"],categories:["version-control","api"],tags:["github","git","repositories","issues","pull-requests"],tools:["create_repository","list_commits","create_issue","create_pull_request"],verified:!0},{id:"postgres",name:"PostgreSQL",description:"PostgreSQL database query and management",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-postgres",command:"npx",args:["-y","@modelcontextprotocol/server-postgres"],requiredEnvVars:["DATABASE_URL"],transports:["stdio"],categories:["database"],tags:["postgres","postgresql","sql","database","query"],tools:["query","list_tables","describe_table"],verified:!0},{id:"sqlite",name:"SQLite",description:"SQLite database operations and queries",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-sqlite",command:"npx",args:["-y","@modelcontextprotocol/server-sqlite"],transports:["stdio"],categories:["database"],tags:["sqlite","sql","database","local"],tools:["query","list_tables","describe_table"],verified:!0},{id:"brave-search",name:"Brave Search",description:"Web search using Brave Search API",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-brave-search",command:"npx",args:["-y","@modelcontextprotocol/server-brave-search"],requiredEnvVars:["BRAVE_API_KEY"],transports:["stdio"],categories:["search","api"],tags:["search","web","brave","internet"],tools:["web_search","local_search"],verified:!0},{id:"puppeteer",name:"Puppeteer",description:"Web scraping and browser automation",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-puppeteer",command:"npx",args:["-y","@modelcontextprotocol/server-puppeteer"],transports:["stdio"],categories:["automation","web"],tags:["browser","scraping","automation","puppeteer"],tools:["navigate","screenshot","click","type","get_content"],verified:!0},{id:"git",name:"Git",description:"Git repository operations and version control",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-git",command:"npx",args:["-y","@modelcontextprotocol/server-git"],transports:["stdio"],categories:["version-control"],tags:["git","vcs","commits","branches"],tools:["git_status","git_log","git_diff","git_commit"],verified:!0},{id:"memory",name:"Memory",description:"Persistent memory and knowledge storage",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-memory",command:"npx",args:["-y","@modelcontextprotocol/server-memory"],transports:["stdio"],categories:["memory","storage"],tags:["memory","knowledge","storage","persistent"],tools:["store","retrieve","search","delete"],verified:!0},{id:"slack",name:"Slack",description:"Slack workspace integration",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-slack",command:"npx",args:["-y","@modelcontextprotocol/server-slack"],requiredEnvVars:["SLACK_BOT_TOKEN"],transports:["stdio"],categories:["communication","api"],tags:["slack","messaging","chat","team"],tools:["send_message","list_channels","get_channel_history"],verified:!0},{id:"google-drive",name:"Google Drive",description:"Google Drive file management",version:"1.0.0",npmPackage:"@modelcontextprotocol/server-gdrive",command:"npx",args:["-y","@modelcontextprotocol/server-gdrive"],transports:["stdio"],categories:["file-system","api"],tags:["google","drive","files","cloud"],tools:["list_files","read_file","create_file","search_files"],verified:!0}],Fw=class extends _r{config;cache=new Map;customEntries=new Map;constructor(e={}){super(),this.config={registries:e.registries??[{type:"official",enableCache:!0}],enableCache:e.enableCache??!0,defaultCacheTTL:e.defaultCacheTTL??36e5,timeout:e.timeout??1e4,userAgent:e.userAgent??"NeuroLink-MCP-Registry-Client/1.0"}}async search(e={}){let{query:t,categories:n,tags:o,transport:s,verifiedOnly:i=!1,sortBy:a="downloads",sortDirection:l="desc",limit:u=25,offset:d=0}=e,p=Math.max(1,u),m=Math.max(0,d),f=await this.getAllEntries();if(t){let y=t.toLowerCase();f=f.filter(v=>v.name.toLowerCase().includes(y)||v.description.toLowerCase().includes(y)||v.tags?.some(b=>b.toLowerCase().includes(y)))}n?.length&&(f=f.filter(y=>y.categories?.some(v=>n.includes(v)))),o?.length&&(f=f.filter(y=>y.tags?.some(v=>o.includes(v)))),s&&(f=f.filter(y=>y.transports?.includes(s))),i&&(f=f.filter(y=>y.verified)),f.sort((y,v)=>{let b=0;switch(a){case"name":b=y.name.localeCompare(v.name);break;case"downloads":b=(y.downloads??0)-(v.downloads??0);break;case"stars":b=(y.stars??0)-(v.stars??0);break;case"lastUpdated":b=(y.lastUpdated??"").localeCompare(v.lastUpdated??"");break}return l==="desc"?-b:b});let h=f.length;return f=f.slice(m,m+p),{entries:f,totalCount:h,page:Math.floor(m/p)+1,pageSize:p,hasMore:m+f.length<h}}async getEntry(e){if(this.customEntries.has(e))return this.customEntries.get(e);let t=ej.find(n=>n.id===e);if(t)return t}async getAllEntries(){let e="all-entries";if(this.config.enableCache){let o=this.cache.get(e);if(o&&Date.now()-o.timestamp<this.config.defaultCacheTTL)return o.data}let t=new Set(this.customEntries.keys()),n=[...ej.filter(o=>!t.has(o.id)),...Array.from(this.customEntries.values())];return this.config.enableCache&&this.cache.set(e,{data:n,timestamp:Date.now()}),n}async getByCategory(e){return(await this.getAllEntries()).filter(n=>n.categories?.includes(e))}async getByTag(e){return(await this.getAllEntries()).filter(n=>n.tags?.includes(e))}async getCategories(){let e=await this.getAllEntries(),t=new Set;for(let n of e)for(let o of n.categories??[])t.add(o);return Array.from(t).sort()}async getTags(){let e=await this.getAllEntries(),t=new Set;for(let n of e)for(let o of n.tags??[])t.add(o);return Array.from(t).sort()}toServerInfo(e){return{id:e.id,name:e.name,description:e.description,command:e.command,args:e.args,transport:e.transports?.[0]??"stdio",status:"stopped",tools:e.tools?.map(t=>({name:t,description:`Tool: ${t}`}))??[],metadata:{...e.metadata,version:e.version,author:e.author,license:e.license,homepage:e.homepage,repository:e.repository,npmPackage:e.npmPackage,requiredEnvVars:e.requiredEnvVars,categories:e.categories,tags:e.tags,verified:e.verified}}}addCustomEntry(e){this.customEntries.set(e.id,e),this.clearCache(),this.emit("entryAdded",{entry:e})}removeCustomEntry(e){let t=this.customEntries.delete(e);return t&&(this.clearCache(),this.emit("entryRemoved",{id:e})),t}addRegistry(e){this.config.registries.push(e),this.clearCache();let{authToken:t,...n}=e;this.emit("registryAdded",{config:n})}clearCache(){this.cache.clear(),this.emit("cacheCleared")}checkRequiredEnvVars(e){let t=[];for(let n of e.requiredEnvVars??[])process.env[n]||t.push(n);return{ready:t.length===0,missing:t}}getInstallCommand(e){if(e.installCommand)return e.installCommand;if(e.npmPackage)return`npx -y ${e.npmPackage}`}async getPopularServers(e=10){return(await this.search({sortBy:"downloads",sortDirection:"desc",limit:e})).entries}async getVerifiedServers(){return(await this.search({verifiedOnly:!0})).entries}async getStatistics(){let e=await this.getAllEntries(),t=await this.getCategories(),n=await this.getTags();return{totalEntries:e.length,verifiedEntries:e.filter(o=>o.verified).length,categories:t.length,tags:n.length,customEntries:this.customEntries.size}}},ste=new Fw});var pte={};le(pte,{AgentExposureManager:()=>Uw,exposeAgentAsTool:()=>qA,exposeAgentsAsTools:()=>lte,exposeWorkflowAsTool:()=>VA,exposeWorkflowsAsTools:()=>ute,globalAgentExposureManager:()=>dte});function qA(r,e={}){let{prefix:t="agent",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:s=v=>v.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:i=!0,executionTimeout:a=3e5,enableLogging:l=!0}=e,u=s(r.name),d=t?`${t}_${u}`:u,p=r.description;if(o&&r.metadata){let v=[];r.metadata.version&&v.push(`v${r.metadata.version}`),r.metadata.category&&v.push(`category: ${r.metadata.category}`),r.metadata.estimatedDuration&&v.push(`~${r.metadata.estimatedDuration}ms`),v.length>0&&(p+=` [${v.join(", ")}]`)}let m={...n,complexity:n.complexity??"complex",estimatedDuration:r.metadata?.estimatedDuration??n.estimatedDuration,costHint:r.metadata?.costHint??n.costHint,tags:[...n.tags??[],"agent",...r.metadata?.tags??[]]},f=r.inputSchema??{type:"object",properties:{}},h=async(v,b)=>{let S=Date.now();l&&g.debug(`[AgentExposure] Executing agent '${r.id}' as tool '${d}'`);try{let w=b?.config&&typeof b.config=="object"?b.config:{},_=i?{...b,config:{...w,sourceType:"mcp-exposed-agent",agentId:r.id,toolName:d}}:b??{},C=await Mn(r.execute(v,_),a),R=Date.now()-S;return l&&g.debug(`[AgentExposure] Agent '${r.id}' completed in ${R}ms`),{success:!0,data:C,metadata:{agentId:r.id,toolName:d,executionTime:R,sourceType:"agent"}}}catch(w){let _=Date.now()-S,C=w instanceof Error?w:pe.toolExecutionFailed(d,new Error(String(w)));return l&&g.error(`[AgentExposure] Agent '${r.id}' failed after ${_}ms: ${C.message}`),{success:!1,error:C.message,metadata:{agentId:r.id,toolName:d,executionTime:_,sourceType:"agent"}}}};return{tool:{name:d,description:p,inputSchema:f,outputSchema:r.outputSchema,annotations:m,execute:h,metadata:{sourceType:"agent",sourceId:r.id,originalName:r.name,...r.metadata}},sourceType:"agent",sourceId:r.id,toolName:d}}function VA(r,e={}){let{prefix:t="workflow",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:s=v=>v.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:i=!0,executionTimeout:a=6e5,enableLogging:l=!0}=e,u=s(r.name),d=t?`${t}_${u}`:u,p=r.description;if(o){let v=[];r.metadata?.version&&v.push(`v${r.metadata.version}`),r.steps?.length&&v.push(`${r.steps.length} steps`),r.metadata?.estimatedDuration&&v.push(`~${r.metadata.estimatedDuration}ms`),v.length>0&&(p+=` [${v.join(", ")}]`)}let m={...n,complexity:n.complexity??"complex",estimatedDuration:r.metadata?.estimatedDuration??n.estimatedDuration,idempotentHint:r.metadata?.idempotent??n.idempotentHint,tags:[...n.tags??[],"workflow",...r.metadata?.tags??[]]},f=r.inputSchema??{type:"object",properties:{}},h=async(v,b)=>{let S=Date.now();l&&g.debug(`[WorkflowExposure] Executing workflow '${r.id}' as tool '${d}'`);try{let w=b?.config&&typeof b.config=="object"?b.config:{},_=i?{...b,config:{...w,sourceType:"mcp-exposed-workflow",workflowId:r.id,toolName:d}}:b??{},C=await Mn(r.execute(v,_),a),R=Date.now()-S;return l&&g.debug(`[WorkflowExposure] Workflow '${r.id}' completed in ${R}ms`),{success:!0,data:C,metadata:{workflowId:r.id,toolName:d,executionTime:R,sourceType:"workflow",stepsCount:r.steps?.length}}}catch(w){let _=Date.now()-S,C=w instanceof Error?w:pe.toolExecutionFailed(d,new Error(String(w)));return l&&g.error(`[WorkflowExposure] Workflow '${r.id}' failed after ${_}ms: ${C.message}`),{success:!1,error:C.message,metadata:{workflowId:r.id,toolName:d,executionTime:_,sourceType:"workflow"}}}};return{tool:{name:d,description:p,inputSchema:f,outputSchema:r.outputSchema,annotations:m,execute:h,metadata:{sourceType:"workflow",sourceId:r.id,originalName:r.name,steps:r.steps,...r.metadata}},sourceType:"workflow",sourceId:r.id,toolName:d}}function lte(r,e={}){return r.map(t=>qA(t,e))}function ute(r,e={}){return r.map(t=>VA(t,e))}var Uw,dte,tj=A(()=>{"use strict";Q();Vl();bt();Uw=class{exposedTools=new Map;options;constructor(e={}){this.options=e}exposeAgent(e){let t=qA(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}exposeWorkflow(e){let t=VA(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}getExposedTools(){return Array.from(this.exposedTools.values()).map(e=>e.tool)}getExposedTool(e){return this.exposedTools.get(e)?.tool}getExposureResult(e){return this.exposedTools.get(e)}getToolsBySourceType(e){return Array.from(this.exposedTools.values()).filter(t=>t.sourceType===e).map(t=>t.tool)}unexpose(e){return this.exposedTools.delete(e)}clear(){this.exposedTools.clear()}getStatistics(){let e=Array.from(this.exposedTools.values());return{totalExposed:e.length,exposedAgents:e.filter(t=>t.sourceType==="agent").length,exposedWorkflows:e.filter(t=>t.sourceType==="workflow").length,toolNames:e.map(t=>t.toolName)}}},dte=new Uw});var G1e={};le(G1e,{ToolIntegrationManager:()=>$w,confirmationMiddleware:()=>gte,createElicitationContext:()=>GA,createRetryMiddleware:()=>yte,createTimeoutMiddleware:()=>hte,createToolMiddlewareChain:()=>rj,globalToolIntegrationManager:()=>xte,loggingMiddleware:()=>fte,validationMiddleware:()=>vte,wrapToolWithElicitation:()=>HA,wrapToolsWithElicitation:()=>mte});function GA(r,e,t){return{confirm:async(n,o)=>t.confirm(n,{toolName:r,serverId:e,confirmLabel:o?.confirmLabel,cancelLabel:o?.cancelLabel}),getText:async(n,o)=>t.getText(n,{toolName:r,placeholder:o?.placeholder,defaultValue:o?.defaultValue}),select:async(n,o)=>t.select(n,o,{toolName:r}),multiSelect:async(n,o)=>t.multiSelect(n,o,{toolName:r}),form:async(n,o)=>t.form(n,o,{toolName:r,serverId:e}),request:async n=>t.request({...n,toolName:r,serverId:e})}}function HA(r,e={}){let{elicitationManager:t,autoConfirmDestructive:n=!1,elicitationTimeout:o=6e4,enableLogging:s=!0}=e,i=t??new vp({defaultTimeout:o});return{...r,execute:async(a,l)=>{let d=l?.config?.serverId,p=GA(r.name,d,i);if((r.annotations?.requiresConfirmation||r.annotations?.destructiveHint)&&!n&&(s&&g.debug(`[ToolIntegration] Tool '${r.name}' requires confirmation`),!await p.confirm(`This operation (${r.name}) ${r.annotations?.destructiveHint?"is destructive and ":""}requires confirmation. Do you want to proceed?`,{confirmLabel:"Yes, proceed",cancelLabel:"Cancel"})))return{success:!1,error:"Operation cancelled by user",metadata:{toolName:r.name,cancelled:!0}};let f={...l,elicitation:p,toolMeta:{name:r.name,serverId:d,annotations:r.annotations}};return r.execute(a,f)}}}function mte(r,e={}){return r.map(t=>HA(t,e))}function rj(r){return async(e,t,n,o)=>{let s=async i=>{if(i>=r.length)return o();let a=r[i];return a(e,t,n,()=>s(i+1))};return s(0)}}function hte(r){return async(e,t,n,o)=>Oe(o(),r,pe.toolTimeout(e.name,r))}function yte(r,e=1e3){return async(t,n,o,s)=>{if(!(t.annotations?.idempotentHint||t.annotations?.readOnlyHint))return s();let a=Math.max(0,r),l;for(let u=0;u<=a;u++)try{return await s()}catch(d){l=d instanceof Error?d:pe.toolExecutionFailed(t.name,new Error(String(d))),u<a&&(g.warn(`[ToolMiddleware] Tool '${t.name}' failed, retrying (${u+1}/${a})`),await new Promise(p=>setTimeout(p,e*(u+1))))}throw l??pe.toolExecutionFailed(t.name,new Error("Retry middleware exhausted without captured error"))}}var fte,gte,vte,$w,xte,bte=A(()=>{"use strict";QB();bt();Q();fte=async(r,e,t,n)=>{let o=Date.now();g.debug(`[ToolMiddleware] Executing tool '${r.name}'`);try{let s=await n(),i=Date.now()-o;return g.debug(`[ToolMiddleware] Tool '${r.name}' completed in ${i}ms`),s}catch(s){let i=Date.now()-o;throw g.error(`[ToolMiddleware] Tool '${r.name}' failed after ${i}ms:`,s),s}},gte=async(r,e,t,n)=>t.elicitation?.confirm&&(r.annotations?.destructiveHint||r.annotations?.requiresConfirmation)&&!await t.elicitation.confirm(`Confirm execution of ${r.name}?`)?{success:!1,error:"Operation cancelled by user",metadata:{cancelled:!0}}:n();vte=async(r,e,t,n)=>{if(!r.inputSchema)return n();let o=r.inputSchema,s=o.required??[],i=o.properties??{},a=e??{},l=[];for(let u of s)a[u]===void 0&&l.push(u);if(l.length>0){let u=l.map(p=>{let m=i[p];return{name:p,label:p,type:m?.type??"text",required:!0,description:m?.description}}),d=await t.elicitation.form(`Missing required parameters for ${r.name}`,u);if(!d)return{success:!1,error:`Missing required parameters: ${l.join(", ")}`,metadata:{missingParams:l}};Object.assign(a,d)}return n()},$w=class{elicitationManager;middlewares=[];wrappedTools=new Map;constructor(e){this.elicitationManager=e??new vp}setElicitationHandler(e){this.elicitationManager.setHandler(e)}use(e){return this.middlewares.push(e),this}registerTool(e){let t=HA(e,{elicitationManager:this.elicitationManager});return this.wrappedTools.set(e.name,t),t}async executeTool(e,t,n){let o=this.wrappedTools.get(e);if(!o)throw pe.toolNotFound(e,Array.from(this.wrappedTools.keys()));let s=t&&typeof t=="object"?t:{},a=n?.config?.serverId,l=GA(e,a,this.elicitationManager),u={...n,elicitation:l,toolMeta:{name:e,serverId:a,annotations:o.annotations}};return this.middlewares.length===0?o.execute(s,u):rj(this.middlewares)(o,s,u,()=>o.execute(s,u))}getTool(e){return this.wrappedTools.get(e)}getAllTools(){return Array.from(this.wrappedTools.values())}getElicitationManager(){return this.elicitationManager}},xte=new $w});var Ate={};le(Ate,{TOOL_COMPATIBILITY:()=>Rte,batchConvertToMCP:()=>wte,batchConvertToNeuroLink:()=>_te,createToolFromFunction:()=>Ete,mcpProtocolToolToServerTool:()=>Tte,mcpToolToNeuroLink:()=>oj,neuroLinkToolToMCP:()=>nj,sanitizeToolName:()=>kte,serverToolToMCPProtocol:()=>Ste,validateToolName:()=>Cte});function nj(r,e={}){let{inferAnnotations:t=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:s}=e,i=s?`${s}_${r.name}`:r.name,a=t?ul({name:r.name,description:r.description}):{},l={...n,...a};r.tags?.length&&(l.tags=[...new Set([...l.tags??[],...r.tags])]);let u=r.parameters??{type:"object",properties:{}},d=o?{...r.metadata}:{};return r.category&&(d.category=r.category),r.isAsync!==void 0&&(d.isAsync=r.isAsync),{name:i,description:r.description,inputSchema:u,annotations:l,execute:r.execute,metadata:d}}function oj(r,e={}){let{removeNamespacePrefix:t}=e,n=r.name;return t&&r.name.startsWith(`${t}_`)&&(n=r.name.slice(t.length+1)),{name:n,description:r.description,parameters:r.inputSchema,execute:r.execute,category:r.metadata?.category,tags:r.annotations?.tags,metadata:r.metadata}}function Tte(r,e,t={}){let{inferAnnotations:n=!0,defaultAnnotations:o={}}=t,s=r.annotations??{},i=n?ul({name:r.name,description:r.description??""}):{},a={...o,...i,title:s.title??i.title??o.title,readOnlyHint:s.readOnlyHint??i.readOnlyHint??o.readOnlyHint,destructiveHint:s.destructiveHint??i.destructiveHint??o.destructiveHint,idempotentHint:s.idempotentHint??i.idempotentHint??o.idempotentHint,openWorldHint:s.openWorldHint??i.openWorldHint??o.openWorldHint};return{name:r.name,description:r.description??"No description provided",inputSchema:r.inputSchema,annotations:a,execute:e}}function Ste(r){let e={};r.annotations?.title&&(e.title=r.annotations.title),r.annotations?.readOnlyHint!==void 0&&(e.readOnlyHint=r.annotations.readOnlyHint),r.annotations?.destructiveHint!==void 0&&(e.destructiveHint=r.annotations.destructiveHint),r.annotations?.idempotentHint!==void 0&&(e.idempotentHint=r.annotations.idempotentHint),r.annotations?.openWorldHint!==void 0&&(e.openWorldHint=r.annotations.openWorldHint);let t=r.inputSchema??{type:"object",properties:{}};return{name:r.name,description:r.description,inputSchema:{type:"object",properties:t.properties??{},required:"required"in t?t.required:void 0},annotations:Object.keys(e).length>0?e:void 0}}function wte(r,e={}){return r.map(t=>nj(t,e))}function _te(r,e={}){return r.map(t=>oj(t,e))}function Ete(r,e,t,n){let o=ul({name:r,description:e});return{name:r,description:e,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(s,i)=>await Mn(t(s,i),3e4,`Tool '${r}' execution timed out after 30000ms`),metadata:n?.metadata}}function Cte(r){let e=[];return!r||typeof r!="string"?e.push("Tool name is required and must be a string"):(r.length>64&&e.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(r)||e.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:e.length===0,errors:e}}function kte(r){let e=r.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(e)||(e=`_${e}`),e.length>64&&(e=e.slice(0,64)),e}var Rte,sj=A(()=>{"use strict";JS();Vl();Rte={MCP_2024_11_05:{annotations:!0,inputSchema:!0,outputSchema:!1,streamingResults:!1,batchExecution:!1},NEUROLINK:{annotations:!0,inputSchema:!0,outputSchema:!0,streamingResults:!0,batchExecution:!0,categories:!0,tags:!0}}});async function H1e(r){let e=r.url?`url:${r.url.replace(/:\/\/[^:]+:[^@]+@/,"://[redacted]@")}`:`${r.host}:${r.port}:${r.db}:${r.password?"auth":"noauth"}`,t=sd.get(e);if(t&&t.client.isOpen)return t.refCount++,g.debug("[Redis] Reusing pooled connection",{key:e,refCount:t.refCount}),t.client;let n=Ite.get(e);if(n){let s=await n,i=sd.get(e);if(i){if(!i.client.isOpen){sd.delete(e);let a=await Pte(r);return sd.set(e,{client:a,refCount:1}),a}i.refCount++}else if(s.isOpen)sd.set(e,{client:s,refCount:1});else{let a=await Pte(r);return sd.set(e,{client:a,refCount:1}),a}return s}t&&sd.delete(e);let o=Pte(r);Ite.set(e,o);try{let s=await o;return sd.set(e,{client:s,refCount:1}),g.info("[Redis] Created pooled connection",{key:e,refCount:1}),s}finally{Ite.delete(e)}}async function W1e(r){let e=`${r.host}:${r.port}:${r.db}:${r.password?"auth":"noauth"}`,t=sd.get(e);if(t&&(t.refCount--,g.debug("[Redis] Released pooled connection",{key:e,refCount:t.refCount}),t.refCount<=0)){try{t.client.isOpen&&await t.client.quit()}catch(n){g.warn("[Redis] Error closing pooled connection",{key:e,error:String(n)})}sd.delete(e),g.info("[Redis] Closed pooled connection",{key:e})}}function ctr(){return Array.from(sd.entries()).map(([r,e])=>({key:r,refCount:e.refCount,isOpen:e.client.isOpen}))}async function Pte(r){let t={url:r.url||`redis://${r.host}:${r.port}/${r.db}`,socket:{connectTimeout:r.connectionOptions?.connectTimeout,reconnectStrategy:o=>o>(r.connectionOptions?.maxRetriesPerRequest||3)?(g.error("Redis connection retries exhausted"),new Error("Redis connection retries exhausted")):Math.min((r.connectionOptions?.retryDelayOnFailover||100)*2**o,1e4)}};r.password&&!r.url&&(t.password=r.password);let n=kA(t);return n.on("error",o=>{let s=o.message.replace(/redis:\/\/.*?@/g,"redis://[redacted]@");g.error("Redis client error",{error:s})}),n.on("connect",()=>{g.debug("Redis client connected",{host:r.host,port:r.port,db:r.db})}),n.on("reconnecting",()=>{g.debug("Redis client reconnecting")}),n.isOpen||await n.connect(),n}function ml(r,e,t){if(!t)return g.warn("[REDIS] getSessionKey called without userId",{sessionId:e}),`${r.keyPrefix}${atr}${e}`;let n=`${r.keyPrefix}${t}:${e}`;return g.debug("[redisUtils] Generated session key",{sessionId:e,userId:t,keyPrefix:r.keyPrefix,fullKey:n}),n}function ij(r,e){return`${r.userSessionsKeyPrefix}${e}`}function zw(r){try{return JSON.stringify(r)}catch(e){throw g.error("[redisUtils] Failed to serialize conversation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,sessionId:r?.sessionId,userId:r?.userId}),e}}function fl(r){if(!r)return null;try{let e=JSON.parse(String(r));if(typeof e!="object"||e===null||!("title"in e)||!("sessionId"in e)||!("userId"in e)||!("createdAt"in e)||!("updatedAt"in e)||!("messages"in e))return g.warn("[redisUtils] Deserialized data is not a valid conversation object",{type:typeof e,hasRequiredFields:e&&typeof e=="object"?Object.keys(e).join(", "):"none",preview:JSON.stringify(e).substring(0,100)}),null;let t=e;return Array.isArray(t.messages)?t.messages.every(o=>typeof o=="object"&&o!==null&&"role"in o&&"content"in o&&typeof o.role=="string"&&typeof o.content=="string"&&(o.role==="user"||o.role==="assistant"||o.role==="system"||o.role==="tool_call"||o.role==="tool_result"))?(g.debug("[redisUtils] Conversation deserialized successfully",{sessionId:t.sessionId,userId:t.userId,title:t.title,messageCount:t.messages.length,createdAt:t.createdAt,updatedAt:t.updatedAt}),t):(g.warn("[redisUtils] Invalid messages structure",{messageCount:t.messages.length,firstMessage:t.messages.length>0?JSON.stringify(t.messages[0]):null}),null):(g.warn("[redisUtils] messages is not an array",{type:typeof t.messages}),null)}catch(e){return g.error("[redisUtils] Failed to deserialize conversation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,dataLength:r.length,dataPreview:"[REDACTED]"}),null}}async function aj(r,e,t=100){g.debug("[redisUtils] Starting SCAN operation",{pattern:e,batchSize:t});let n=[],o="0",s=0,i=0;try{do{s++;let a=await r.scan(o,{MATCH:e,COUNT:t});o=String(a.cursor);let l=(a.keys||[]).map(String);n.push(...l),i+=l.length,g.debug("[redisUtils] SCAN iteration completed",{iteration:s,currentCursor:o,keysInBatch:l.length,totalKeysFound:n.length})}while(o!=="0");return g.info("[redisUtils] SCAN operation completed",{pattern:e,totalIterations:s,totalKeysFound:n.length,totalScanned:i}),n}catch(a){throw g.error("[redisUtils] Error during SCAN operation",{pattern:e,error:a instanceof Error?a.message:String(a),stack:a instanceof Error?a.stack:void 0}),a}}function K1e(r){let e=r.keyPrefix||"neurolink:conversation:",t=e.replace(/conversation:?$/,"user:sessions:"),n=r.host||"localhost",o=r.port||6379,s=r.username||"",i=r.password||"",a=r.db||0,l=r.url;if(l)try{let u=new URL(l);n=u.hostname,o=u.port?parseInt(u.port):6379,s=u.username||s,i=u.password||i,a=u.pathname&&parseInt(u.pathname.replace("/",""))||0}catch(u){let d=l.replace(/:\/\/[^@]+@/,"://[redacted]@");g.warn("[redisUtils] Failed to parse Redis URL, falling back to component-based connection",{url:d,error:u instanceof Error?u.message:String(u)}),l=void 0}return{url:l||"",host:n,port:o,password:i,username:s,db:a,keyPrefix:e,userSessionsKeyPrefix:r.userSessionsKeyPrefix||t,ttl:r.ttl||86400,connectionOptions:{connectTimeout:3e4,lazyConnect:!0,retryDelayOnFailover:100,maxRetriesPerRequest:3,...r.connectionOptions}}}var atr,sd,Ite,Mte=A(()=>{"use strict";SB();Q();atr="session-only:",sd=new Map,Ite=new Map});var WA,Ote,cj,J1e=A(async()=>{"use strict";Kt();tr();dr();O$();BQ();XY();await sz();vr();bt();pv();wm();Q();Mte();WA=ye.redis,Ote=5e3,cj=class{config;isInitialized=!1;summarizationEngine=new WS;redisConfig;redisClient=null;pendingToolExecutions=new Map;titleGenerationInProgress=new Set;summarizationInProgress=new Set;constructor(e,t={}){this.config=e,this.redisConfig=K1e(t)}async initialize(){if(this.isInitialized){g.debug("[RedisConversationMemoryManager] Already initialized, skipping");return}await WA.startActiveSpan("neurolink.memory.initialize",{kind:er.CLIENT,attributes:{"redis.host":this.redisConfig.host,"redis.port":this.redisConfig.port,"redis.key_prefix":this.redisConfig.keyPrefix}},async e=>{try{g.debug("[RedisConversationMemoryManager] Initializing with config",{host:this.redisConfig.host,port:this.redisConfig.port,keyPrefix:this.redisConfig.keyPrefix,ttl:this.redisConfig.ttl}),this.redisClient=await H1e(this.redisConfig),this.isInitialized=!0,g.info("RedisConversationMemoryManager initialized",{storage:"redis",host:this.redisConfig.host,port:this.redisConfig.port,maxSessions:this.config.maxSessions,maxTurnsPerSession:this.config.maxTurnsPerSession}),g.debug("[RedisConversationMemoryManager] Redis client created successfully",{clientType:this.redisClient?.constructor?.name||"unknown",isConnected:!!this.redisClient})}catch(t){throw e.setStatus({code:be.ERROR,message:t instanceof Error?t.message:String(t)}),e.recordException(t instanceof Error?t:new Error(String(t))),g.error("[RedisConversationMemoryManager] Failed to initialize",{error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,config:{host:this.redisConfig.host,port:this.redisConfig.port}}),new qi("Failed to initialize Redis conversation memory","CONFIG_ERROR",{error:t instanceof Error?t.message:String(t)})}finally{e.end()}})}get canPersist(){return this.isInitialized&&this.redisClient!==null&&this.redisClient.isOpen}get isRedisConfigured(){return this.redisClient!==null&&this.redisClient.isOpen}getHealthStatus(){return{initialized:this.isInitialized,connected:this.redisClient?.isOpen??!1,host:this.redisConfig.host,keyPrefix:this.redisConfig.keyPrefix}}async getSession(e,t,n){if(await this.ensureInitialized(),!this.redisClient)return;let o=this.redisClient;return WA.startActiveSpan("neurolink.memory.getSession",{kind:er.CLIENT,attributes:{"session.id":e}},async s=>{t&&s.setAttribute("user.id",t);try{let i=ml(this.redisConfig,e,t),a=await Oe(o.get(i),Ote),l=fl(a||null);if(!l){s.setAttribute("session.found",!1);return}s.setAttribute("session.found",!0);let u=a?Buffer.byteLength(a,"utf8"):0,d=l.messages.length,p=!!l.summarizedUpToMessageId,m=p?l.messages.findIndex(h=>h.id===l.summarizedUpToMessageId):-1,f=p&&m!==-1?d-m-1:d;return s.setAttribute("message.count",d),s.setAttribute("blob.size_bytes",u),g.info("[ConversationMemory] Session loaded",{requestId:n,sessionId:e,blobSizeBytes:u,messageCount:d,hasSummary:p,recentMessageCount:f}),u>512*1024&&g.warn("[ConversationMemory] Large session blob",{requestId:n,sessionId:e,blobSizeBytes:u,messageCount:d}),{sessionId:l.sessionId,userId:l.userId,messages:l.messages,summarizedUpToMessageId:l.summarizedUpToMessageId,summarizedMessage:l.summarizedMessage,tokenThreshold:l.tokenThreshold,lastTokenCount:l.lastTokenCount,lastCountedAt:l.lastCountedAt,lastApiTokenCount:l.lastApiTokenCount,createdAt:new Date(l.createdAt).getTime(),lastActivity:new Date(l.updatedAt).getTime()}}catch(i){s.setStatus({code:be.ERROR,message:i instanceof Error?i.message:String(i)}),s.recordException(i instanceof Error?i:new Error(String(i))),g.error("[RedisConversationMemoryManager] Failed to get session",{sessionId:e,userId:t,error:i instanceof Error?i.message:String(i)});return}finally{s.end()}})}async getSessionRaw(e,t){try{if(await this.ensureInitialized(),!this.redisClient)return null;let n=ml(this.redisConfig,e,t),o=await this.redisClient.get(n);return fl(o||null)}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get raw session",{sessionId:e,userId:t,error:n instanceof Error?n.message:String(n)}),null}}async getUserSessions(e){if(await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];try{let t=ij(this.redisConfig,e),n=await this.redisClient.sMembers(t);return Array.from(n).map(String)}catch(t){return g.error("[RedisConversationMemoryManager] Failed to get user sessions",{userId:e,error:t instanceof Error?t.message:String(t)}),[]}}async addUserSession(e,t){if(!(!this.redisClient||!e))try{let n=ij(this.redisConfig,e);await this.redisClient.sAdd(n,t),this.redisConfig.ttl>0&&await this.redisClient.expire(n,this.redisConfig.ttl)}catch(n){g.error("[RedisConversationMemoryManager] Failed to add session to user set",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n)})}}async removeUserSession(e,t){if(!this.redisClient||!e)return!1;try{let n=ij(this.redisConfig,e),o=await this.redisClient.sRem(n,t);return Number(o)>0}catch(n){return g.error("[RedisConversationMemoryManager] Failed to remove session from user set",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n)}),!1}}generateTimestamp(){return new Date().toISOString()}async storeToolExecution(e,t,n,o,s){g.debug("[RedisConversationMemoryManager] Storing tool execution temporarily",{sessionId:e,userId:t,toolCallsCount:n?.length||0,toolResultsCount:o?.length||0});try{let i=t||"randomUser",a=`${e}:${i}`,l={toolCalls:(n||[]).map(d=>({...d,timestamp:s})),toolResults:(o||[]).map(d=>({...d,timestamp:s})),timestamp:Date.now()},u=this.pendingToolExecutions.get(a);u&&(g.debug("[RedisConversationMemoryManager] Merging with existing pending tool data",{sessionId:e,existingToolCalls:u.toolCalls.length,existingToolResults:u.toolResults.length,newToolCalls:n?.length||0,newToolResults:o?.length||0}),l.toolCalls=[...u.toolCalls,...l.toolCalls],l.toolResults=[...u.toolResults,...l.toolResults]),this.pendingToolExecutions.set(a,l),g.debug("[RedisConversationMemoryManager] Tool execution stored temporarily",{sessionId:e,userId:i,pendingKey:a,totalToolCalls:l.toolCalls.length,totalToolResults:l.toolResults.length}),this.cleanupStalePendingData()}catch(i){g.error("[RedisConversationMemoryManager] Failed to store tool execution temporarily",{sessionId:e,error:i instanceof Error?i.message:String(i)})}}async storeConversationTurn(e){return g.debug("[RedisConversationMemoryManager] Storing conversation turn",{sessionId:e.sessionId,userId:e.userId}),await this.ensureInitialized(),WA.startActiveSpan("neurolink.memory.storeTurn",{kind:er.CLIENT,attributes:{"session.id":e.sessionId,...e.userId&&{"user.id":e.userId}}},async t=>{try{if(!this.redisClient)throw new Error("Redis client not initialized");let n=ml(this.redisConfig,e.sessionId,e.userId),o=await this.redisClient.get(n),s=fl(o),i=new Date().toISOString(),a=e.userId||"randomUser";if(s)s.updatedAt=i;else{let h=`${e.sessionId}:${a}`,y=Sm(async()=>{if(!this.titleGenerationInProgress.has(h)){this.titleGenerationInProgress.add(h);try{let v=await this.generateConversationTitle(e.userMessage),b=ml(this.redisConfig,e.sessionId,e.userId||void 0),S=await this.redisClient?.get(b),w=fl(S||null);if(w){w.title=v,w.updatedAt=new Date().toISOString();let _=zw(w);await this.redisClient?.set(b,_),this.redisConfig.ttl>0&&await this.redisClient?.expire(b,this.redisConfig.ttl)}}catch(v){g.warn("[RedisConversationMemoryManager] Failed to generate conversation title in background",{sessionId:e.sessionId,userId:a,error:v instanceof Error?v.message:String(v)})}finally{this.titleGenerationInProgress.delete(h)}}});setImmediate(y),s={id:Fe(),title:"New Conversation",sessionId:e.sessionId,userId:a,createdAt:e.startTimeStamp?.toISOString()||i,updatedAt:e.startTimeStamp?.toISOString()||i,messages:[]}}let l=e.providerDetails?nz(e.providerDetails.provider,e.providerDetails.model,this.config.tokenThreshold,s.tokenThreshold):this.config.tokenThreshold||5e4,u={id:Fe(),timestamp:e.startTimeStamp?.toISOString()||this.generateTimestamp(),role:"user",content:e.userMessage};s.messages.push(u),await this.flushPendingToolData(s,e.sessionId,a);let d={id:Fe(),timestamp:this.generateTimestamp(),role:"assistant",content:e.aiResponse,events:e.events||void 0,...e.thoughtSignature&&{metadata:{thoughtSignature:e.thoughtSignature}}};if(s.messages.push(d),e.tokenUsage&&(s.lastApiTokenCount=e.tokenUsage),g.info("[RedisConversationMemoryManager] Added new messages",{sessionId:s.sessionId,userId:s.userId}),e.enableSummarization!==void 0?e.enableSummarization:this.config.enableSummarization){let h=e.userId||"randomUser",y=`${e.sessionId}:${h}`;if(this.summarizationInProgress.has(y))g.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:e.sessionId,userId:h});else{let v=Sm(async()=>{try{await this.checkAndSummarize(s,l,e.sessionId,e.userId,e.requestId)}catch(b){g.error("Background summarization failed",{sessionId:s.sessionId,error:b instanceof Error?b.message:String(b)})}});setImmediate(v)}}let m=zw(s);await this.redisClient.set(n,m);let f=Buffer.byteLength(m,"utf8");g.info("[ConversationMemory] Turn stored",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:f,totalMessages:s.messages.length,userMsgChars:e.userMessage.length,assistantMsgChars:e.aiResponse.length}),f>512*1024&&g.warn("[ConversationMemory] Large session blob",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:f,messageCount:s.messages.length}),this.redisConfig.ttl>0&&await this.redisClient.expire(n,this.redisConfig.ttl),e.userId&&await this.addUserSession(e.userId,e.sessionId),t.setAttribute("message.count",s.messages.length),t.setStatus({code:be.OK}),g.debug("[RedisConversationMemoryManager] Successfully stored conversation turn",{sessionId:e.sessionId,totalMessages:s.messages.length,title:s.title})}catch(n){throw t.setStatus({code:be.ERROR,message:n instanceof Error?n.message:String(n)}),t.recordException(n instanceof Error?n:new Error(String(n))),new qi(`Failed to store conversation turn in Redis for session ${e.sessionId}`,"STORAGE_ERROR",{sessionId:e.sessionId,error:n instanceof Error?n.message:String(n)})}finally{t.end()}})}async checkAndSummarize(e,t,n,o,s){let i=o||"randomUser",a=`${n}:${i}`;if(this.summarizationInProgress.has(a)){g.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:n,userId:i});return}this.summarizationInProgress.add(a);try{let l={sessionId:e.sessionId,userId:e.userId,messages:e.messages,summarizedUpToMessageId:e.summarizedUpToMessageId,summarizedMessage:e.summarizedMessage,tokenThreshold:e.tokenThreshold,lastTokenCount:e.lastTokenCount,lastCountedAt:e.lastCountedAt,createdAt:new Date(e.createdAt).getTime(),lastActivity:new Date(e.updatedAt).getTime()},u=await this.summarizationEngine.checkAndSummarize(l,t,this.config,"[RedisConversationMemoryManager]",s);if(e.lastTokenCount=l.lastTokenCount,e.lastCountedAt=l.lastCountedAt,u&&(e.summarizedUpToMessageId=l.summarizedUpToMessageId,e.summarizedMessage=l.summarizedMessage,this.redisClient)){let d=ml(this.redisConfig,n,o),p=await this.redisClient.get(d);if(p){let m=fl(p);if(m){m.summarizedUpToMessageId=e.summarizedUpToMessageId,m.summarizedMessage=e.summarizedMessage,m.lastTokenCount=e.lastTokenCount,m.lastCountedAt=e.lastCountedAt;let f=zw(m);await this.redisClient.set(d,f),this.redisConfig.ttl>0&&await this.redisClient.expire(d,this.redisConfig.ttl)}}}}catch(l){g.error("Token counting or summarization failed",{sessionId:e.sessionId,error:l instanceof Error?l.message:String(l)})}finally{this.summarizationInProgress.delete(a)}}async buildContextMessages(e,t,n,o){if(g.debug("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,enableSummarization:n}),await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available in buildContextMessages"),[];let s=this.redisClient;return WA.startActiveSpan("neurolink.memory.buildContext",{kind:er.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async i=>{try{g.info("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,method:"buildContextMessages"});let a=ml(this.redisConfig,e,t),l=await Oe(s.get(a),Ote),u=fl(l||null);if(g.debug("[RedisConversationMemoryManager] Retrieved conversation for context building",{sessionId:e,userId:t,conversationFound:!!u}),!u)return i.setAttribute("session.found",!1),i.setStatus({code:be.OK}),[];let d={sessionId:u.sessionId,userId:u.userId,messages:u.messages,summarizedUpToMessageId:u.summarizedUpToMessageId,summarizedMessage:u.summarizedMessage,tokenThreshold:u.tokenThreshold,lastTokenCount:u.lastTokenCount,lastCountedAt:u.lastCountedAt,createdAt:new Date(u.createdAt).getTime(),lastActivity:new Date(u.updatedAt).getTime()},p=GS(d,o);g.debug("[RedisConversationMemoryManager] Built context messages from pointer",{sessionId:e,userId:t,contextMessageCount:p.length,pointerMessageId:d.summarizedUpToMessageId||"none"});let m=this.config?.contextCompaction?.sendToolPreview===!0,f=p.map(h=>{if(h.role!=="tool_result")return h;let y=m&&h.metadata?.toolOutputPreview?h.metadata.toolOutputPreview:h.content,v=h.result;if(h.result&&h.result.result===void 0){let b=y;try{b=JSON.parse(y)}catch{}v={...h.result,result:b}}return g.debug("[RedisConversationMemoryManager] Processing tool_result message for context",{sessionId:e,userId:t,messageId:h.id,sendToolPreview:m,hasPreview:!!h.metadata?.toolOutputPreview,contentLength:y?String(y).length:0,resultHydrated:v!==h.result}),{...h,content:y,result:v}});return i.setAttribute("context.message_count",f.length),i.setStatus({code:be.OK}),g.info("[RedisConversationMemoryManager] Retrieved context messages",{sessionId:e,userId:t}),f}catch(a){throw i.setStatus({code:be.ERROR,message:a instanceof Error?a.message:String(a)}),i.recordException(a instanceof Error?a:new Error(String(a))),a}finally{i.end()}})}async getUserSessionMetadata(e,t){if(g.debug("[RedisConversationMemoryManager] Getting user session metadata",{userId:e,sessionId:t}),await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e,sessionId:t}),null;try{let n=ml(this.redisConfig,t,e),o=await this.redisClient.get(n);if(!o)return g.debug("[RedisConversationMemoryManager] No session data found",{userId:e,sessionId:t,sessionKey:n}),null;let s=fl(o);return s?{id:s.sessionId,title:s.title,createdAt:s.createdAt,updatedAt:s.updatedAt,metadata:s.additionalMetadata?.agenticLoopReports?{agenticLoopReports:s.additionalMetadata.agenticLoopReports}:void 0}:(g.debug("[RedisConversationMemoryManager] No valid conversation data found",{userId:e,sessionId:t,sessionKey:n}),null)}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get user session metadata",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0}),null}}async getUserSessionHistory(e,t){g.debug("[RedisConversationMemoryManager] Getting user session history via getUserSessionObject",{userId:e,sessionId:t});try{let n=await this.getUserSessionObject(e,t);return n?n.messages:(g.debug("[RedisConversationMemoryManager] No session object found, returning null",{userId:e,sessionId:t}),null)}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get user session history via getUserSessionObject",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n),errorName:n instanceof Error?n.name:"UnknownError",stack:n instanceof Error?n.stack:void 0}),null}}async getUserSessionObject(e,t){if(g.debug("[RedisConversationMemoryManager] Getting complete user session object",{userId:e,sessionId:t,method:"getUserSessionObject"}),!e||typeof e!="string")return g.warn("[RedisConversationMemoryManager] Invalid userId provided",{userId:e,sessionId:t}),null;if(!t||typeof t!="string")return g.warn("[RedisConversationMemoryManager] Invalid sessionId provided",{userId:e,sessionId:t}),null;if(await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available for getUserSessionObject",{userId:e,sessionId:t}),null;try{let n=ml(this.redisConfig,t,e),o=await this.redisClient.get(n);if(!o)return g.debug("[RedisConversationMemoryManager] No conversation data found in Redis",{userId:e,sessionId:t,sessionKey:n}),null;let s=fl(o);return s?!s.messages||!Array.isArray(s.messages)?(g.warn("[RedisConversationMemoryManager] Invalid conversation structure - missing messages array",{userId:e,sessionId:t,hasMessages:!!s.messages,messagesType:typeof s.messages}),null):s:(g.debug("[RedisConversationMemoryManager] Failed to deserialize conversation data",{userId:e,sessionId:t,sessionKey:n,dataLength:o.length}),null)}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get complete user session object",{userId:e,sessionId:t,error:n instanceof Error?n.message:String(n),errorName:n instanceof Error?n.name:"UnknownError",stack:n instanceof Error?n.stack:void 0}),null}}async generateConversationTitle(e){g.info("[RedisConversationMemoryManager] Generating conversation title",{userMessageLength:e.length,userMessagePreview:e.substring(0,100)});try{let t=new Fv({conversationMemory:{enabled:!1}}),n=`Generate a clear, concise, and descriptive title (20-25 letters maximum) for a conversation based on the following user message.
|
|
2168
2168
|
The title must meaningfully reflect the topic or intent of the message.
|
|
2169
2169
|
Do not output anything unrelated, vague, or generic.
|
|
2170
2170
|
Do not say you cannot create a title. Always return a valid title.
|
|
2171
2171
|
|
|
2172
|
-
User message: "${e}"`,o=await t.generate({input:{text:
|
|
2172
|
+
User message: "${e}"`,o=process.env.NEUROLINK_TITLE_PROMPT,s=o?o.replace(/\$\{userMessage\}/g,e):n,i=await t.generate({input:{text:s},provider:this.config.summarizationProvider||"vertex",model:this.config.summarizationModel||"gemini-2.5-flash",disableTools:!0}),a=i.content?.trim()||"New Conversation";return a=a.replace(/^(Title:|Here's a title:|The title is:)\s*/i,""),a=a.replace(/['"]/g,""),a=a.replace(/\.$/,""),a.length>60&&(a=a.substring(0,57)+"..."),a.length<3&&(a="New Conversation"),g.info("[RedisConversationMemoryManager] Generated conversation title",{originalLength:i.content?.length||0,cleanedTitle:a,titleLength:a.length}),a}catch(t){return g.error("[RedisConversationMemoryManager] Failed to generate conversation title",{error:t instanceof Error?t.message:String(t),userMessagePreview:e.substring(0,100)}),e.length>30?e.substring(0,30)+"...":e||"New Conversation"}}createSummarySystemMessage(e,t,n){return{id:`summary-${Fe()}`,role:"system",content:`Summary of previous conversation turns:
|
|
2173
2173
|
|
|
2174
2174
|
${e}`,timestamp:new Date().toISOString(),metadata:{isSummary:!0,summarizesFrom:t,summarizesTo:n}}}async getSessionMessages(e,t){if(await this.ensureInitialized(),!this.redisClient)return[];try{let n=ml(this.redisConfig,e,t),o=await this.redisClient.get(n);return fl(o||null)?.messages??[]}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get session messages",{sessionId:e,userId:t,error:n instanceof Error?n.message:String(n)}),[]}}async setSessionMessages(e,t,n){if(await this.ensureInitialized(),!this.redisClient)throw new qi("Redis client not initialized","STORAGE_ERROR",{sessionId:e});try{let o=ml(this.redisConfig,e,n),s=await this.redisClient.get(o),i=fl(s||null);if(!i)throw new qi(`Session ${e} not found`,"STORAGE_ERROR",{sessionId:e});i.messages=t,i.updatedAt=new Date().toISOString(),i.summarizedUpToMessageId=void 0,i.summarizedMessage=void 0,i.lastTokenCount=void 0,i.lastCountedAt=void 0;let a=zw(i);await this.redisClient.set(o,a),this.redisConfig.ttl>0&&await this.redisClient.expire(o,this.redisConfig.ttl),g.debug("[RedisConversationMemoryManager] Session messages replaced",{sessionId:e,userId:n,messageCount:t.length})}catch(o){throw o instanceof qi?o:new qi(`Failed to set session messages for session ${e}`,"STORAGE_ERROR",{sessionId:e,error:o instanceof Error?o.message:String(o)})}}async close(){this.redisClient&&(await W1e(this.redisConfig),this.redisClient=null,this.isInitialized=!1,g.info("Redis connection closed"))}async getStats(){if(await this.ensureInitialized(),!this.redisClient)return{totalSessions:0,totalTurns:0};let e=`${this.redisConfig.keyPrefix}*`,t=await aj(this.redisClient,e);g.debug("[RedisConversationMemoryManager] Got session keys with SCAN",{pattern:e,keyCount:t.length});let n=0;for(let o of t){let s=await this.redisClient.get(o),i=fl(s);i?.messages&&(n+=i.messages.length/2)}return{totalSessions:t.length,totalTurns:n}}async clearSession(e,t){if(await this.ensureInitialized(),!this.redisClient)return!1;let n=this.redisClient;return WA.startActiveSpan("neurolink.memory.clear",{kind:er.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async o=>{try{let s=ml(this.redisConfig,e,t),i=await Oe(n.del(s),Ote);return Number(i)>0?(t&&await this.removeUserSession(t,e),o.setAttribute("session.deleted",!0),o.setStatus({code:be.OK}),g.info("Redis session cleared",{sessionId:e}),!0):(o.setAttribute("session.deleted",!1),o.setStatus({code:be.OK}),!1)}catch(s){throw o.setStatus({code:be.ERROR,message:s instanceof Error?s.message:String(s)}),o.recordException(s instanceof Error?s:new Error(String(s))),s}finally{o.end()}})}async clearAllSessions(){if(await this.ensureInitialized(),!this.redisClient)return;let e=`${this.redisConfig.keyPrefix}*`,t=`${this.redisConfig.userSessionsKeyPrefix}*`,n=await aj(this.redisClient,e),o=await aj(this.redisClient,t),s=[...n,...o];if(g.debug("[RedisConversationMemoryManager] Got all keys with SCAN for clearing",{conversationPattern:e,userSessionsPattern:t,conversationKeyCount:n.length,userSessionsKeyCount:o.length,totalKeyCount:s.length}),s.length>0){for(let a=0;a<s.length;a+=100){let l=s.slice(a,a+100);await this.redisClient.del(l),g.debug("[RedisConversationMemoryManager] Cleared batch of sessions and user mappings",{batchIndex:Math.floor(a/100)+1,batchSize:l.length,totalProcessed:a+l.length,totalKeys:s.length})}g.info("All Redis sessions and user session mappings cleared",{clearedCount:s.length,conversationSessions:n.length,userSessionMappings:o.length})}}async ensureInitialized(){g.debug("[RedisConversationMemoryManager] Ensuring initialization"),this.isInitialized?g.debug("[RedisConversationMemoryManager] Already initialized"):(g.debug("[RedisConversationMemoryManager] Not initialized, initializing now"),await this.initialize())}async getUserAllSessionsHistory(e){if(await this.ensureInitialized(),!this.redisClient)return g.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];let t=[];try{let n=await this.getUserSessions(e);if(n.length===0)return t;for(let o of n)try{let s=await this.getUserSessionMetadata(e,o);s?t.push(s):(g.debug("[RedisConversationMemoryManager] Empty or missing session metadata - removing from user history",{userId:e,sessionId:o}),await this.removeUserSession(e,o))}catch(s){g.error("[RedisConversationMemoryManager] Failed to get session metadata",{userId:e,sessionId:o,error:s instanceof Error?s.message:String(s)})}return t}catch(n){return g.error("[RedisConversationMemoryManager] Failed to get user all sessions metadata",{userId:e,error:n instanceof Error?n.message:String(n),stack:n instanceof Error?n.stack:void 0}),t}}cleanupStalePendingData(){let e=Date.now()-3e5,t=[];for(let[n,o]of this.pendingToolExecutions)o.timestamp<e&&t.push(n);t.length>0&&(g.debug("[RedisConversationMemoryManager] Cleaning up stale pending tool data",{stalePendingKeys:t.length,totalPendingKeys:this.pendingToolExecutions.size}),t.forEach(n=>this.pendingToolExecutions.delete(n)))}async flushPendingToolData(e,t,n){let o=`${t}:${n}`,s=this.pendingToolExecutions.get(o);if(!s){g.debug("[RedisConversationMemoryManager] No pending tool data to flush",{sessionId:t,userId:n,pendingKey:o});return}g.debug("[RedisConversationMemoryManager] Flushing pending tool data",{sessionId:t,userId:n,toolCallsCount:s.toolCalls.length,toolResultsCount:s.toolResults.length});try{let i=new Map;for(let a of s.toolCalls){let l=a.toolCallId??"",u=a.toolName??"";i.set(l,u);let d={id:Fe(),timestamp:a.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_call",content:"",tool:u,args:a.args||a.arguments||a.parameters||{},metadata:{...a.thoughtSignature?{thoughtSignature:String(a.thoughtSignature)}:{},...a.stepIndex!==null&&a.stepIndex!==void 0?{stepIndex:Number(a.stepIndex)}:{}}};e.messages.push(d)}for(let a of s.toolResults){let l=String(a.toolCallId||a.id||"unknown"),u=i.get(l)||String(a.toolName||"unknown"),d;if(typeof a.result=="string")d=a.result;else if(a.result===void 0||a.result===null)d=String(a.result??"null");else try{d=JSON.stringify(a.result,null,2)}catch(S){d=`[Serialization failed: ${S instanceof Error?S.message:String(S)}]`}let{preview:p,truncated:m,originalSize:f}=_m(d,{maxBytes:this.config?.contextCompaction?.maxToolOutputBytes,maxLines:this.config?.contextCompaction?.maxToolOutputLines}),h;try{let S=a.result;if(S&&typeof S=="object"){let w=S._meta;if(w&&typeof w=="object"){let _=w[iB];typeof _=="string"&&(h=_)}}}catch{}let y={truncated:m,...m&&{toolOutputPreview:p},...m&&{originalSize:f},...h&&{artifactId:h},...a.stepIndex!==null&&a.stepIndex!==void 0?{stepIndex:Number(a.stepIndex)}:{}},v={success:!a.error,error:a.error?String(a.error):void 0},b={id:Fe(),timestamp:a.timestamp?.toISOString()||this.generateTimestamp(),role:"tool_result",content:d,tool:u,result:v,metadata:y};e.messages.push(b)}g.debug("[RedisConversationMemoryManager] Successfully flushed pending tool data",{sessionId:t,userId:n,toolMessagesAdded:s.toolCalls.length+s.toolResults.length,totalMessages:e.messages.length})}finally{this.pendingToolExecutions.delete(o)}}async updateAgenticLoopReport(e,t,n){if(g.debug("[RedisConversationMemoryManager] Updating agentic loop report",{sessionId:e,userId:t,reportId:n.reportId,reportType:n.reportType,reportStatus:n.reportStatus}),await this.ensureInitialized(),!this.redisClient){g.warn("[RedisConversationMemoryManager] Redis client not available for report update",{sessionId:e,userId:t});return}try{let o=ml(this.redisConfig,e,t||void 0),s=await Oe(this.redisClient.get(o),5e3);if(!s){g.warn("[RedisConversationMemoryManager] No conversation found for report update",{sessionId:e,userId:t});return}let i=fl(s);if(!i){g.warn("[RedisConversationMemoryManager] Failed to deserialize conversation for report update",{sessionId:e,userId:t});return}i.additionalMetadata||(i.additionalMetadata={}),i.additionalMetadata.agenticLoopReports||(i.additionalMetadata.agenticLoopReports=[]);let a=i.additionalMetadata.agenticLoopReports.findIndex(u=>u.reportId===n.reportId);a>=0?(i.additionalMetadata.agenticLoopReports[a]=n,g.debug("[RedisConversationMemoryManager] Updated existing agentic loop report",{sessionId:e,reportId:n.reportId})):(i.additionalMetadata.agenticLoopReports.push(n),g.debug("[RedisConversationMemoryManager] Added new agentic loop report",{sessionId:e,reportId:n.reportId})),i.updatedAt=new Date().toISOString();let l=zw(i);await Oe(this.redisClient.set(o,l),5e3),this.redisConfig.ttl>0&&await Oe(this.redisClient.expire(o,this.redisConfig.ttl),5e3),g.info("[RedisConversationMemoryManager] Successfully updated agentic loop report",{sessionId:e,userId:t,reportId:n.reportId,reportStatus:n.reportStatus})}catch(o){throw g.error("[RedisConversationMemoryManager] Failed to update agentic loop report",{sessionId:e,userId:t,reportId:n.reportId,error:o instanceof Error?o.message:String(o)}),new qi("Failed to update agentic loop report","STORAGE_ERROR",{sessionId:e,userId:t,reportId:n.reportId,error:o instanceof Error?o.message:String(o)})}}}});function Nte(r,e="memory",t){if(g.debug("[conversationMemoryFactory] Creating conversation memory manager",{storageType:e,config:{enabled:r.enabled,maxSessions:r.maxSessions,enableSummarization:r.enableSummarization,summarizationProvider:r.summarizationProvider,summarizationModel:r.summarizationModel},hasRedisConfig:!!t}),e==="memory"||!e){g.debug("[conversationMemoryFactory] Creating in-memory conversation manager");let o=new mv(r);return g.debug("[conversationMemoryFactory] In-memory conversation manager created successfully",{managerType:o.constructor.name}),o}if(e==="redis"){g.debug("[conversationMemoryFactory] Creating Redis conversation manager",{host:t?.host||"localhost",port:t?.port||6379,keyPrefix:t?.keyPrefix||"neurolink:conversation:",ttl:t?.ttl||86400,hasConnectionOptions:!!t?.connectionOptions});let o=new cj(r,t);return g.debug("[conversationMemoryFactory] Redis conversation manager created successfully",{managerType:o.constructor.name,config:{maxSessions:r.maxSessions,maxTurnsPerSession:r.maxTurnsPerSession}}),o}g.warn(`[conversationMemoryFactory] Unknown storage type: ${e}, falling back to memory storage`);let n=new mv(r);return g.debug("[conversationMemoryFactory] Fallback memory manager created successfully",{managerType:n.constructor.name}),n}function Z1e(){let r=process.env.STORAGE_TYPE;if(!r)return g.debug("[conversationMemoryFactory] No storage type configured, using default",{storageType:"memory",fromEnv:!1}),"memory";let e=r.trim().toLowerCase(),t=["memory","redis"];return t.includes(e)?(g.debug("[conversationMemoryFactory] Determined storage type",{storageType:e,fromEnv:!0,envValue:r,normalized:e!==r}),e):(g.warn(`[conversationMemoryFactory] Unrecognized storage type in environment: "${r}", falling back to "memory"`,{providedValue:r,normalizedValue:e,validValues:t,usingDefault:!0}),"memory")}function X1e(){g.debug("[conversationMemoryFactory] Reading Redis configuration from environment",{REDIS_URL:process.env.REDIS_URL?"******":"(not set)",REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",REDIS_CONNECT_TIMEOUT:process.env.REDIS_CONNECT_TIMEOUT||"(not set)",REDIS_MAX_RETRIES:process.env.REDIS_MAX_RETRIES||"(not set)",REDIS_RETRY_DELAY:process.env.REDIS_RETRY_DELAY||"(not set)"});let r={host:process.env.REDIS_HOST,port:process.env.REDIS_PORT?Number(process.env.REDIS_PORT):void 0,password:process.env.REDIS_PASSWORD,db:process.env.REDIS_DB?Number(process.env.REDIS_DB):void 0,keyPrefix:process.env.REDIS_KEY_PREFIX,ttl:process.env.REDIS_TTL?Number(process.env.REDIS_TTL):void 0,connectionOptions:{connectTimeout:process.env.REDIS_CONNECT_TIMEOUT?Number(process.env.REDIS_CONNECT_TIMEOUT):void 0,maxRetriesPerRequest:process.env.REDIS_MAX_RETRIES?Number(process.env.REDIS_MAX_RETRIES):void 0,retryDelayOnFailover:process.env.REDIS_RETRY_DELAY?Number(process.env.REDIS_RETRY_DELAY):void 0}};return process.env.REDIS_URL&&(g.debug("[conversationMemoryFactory] Using REDIS_URL for connection"),r.url=process.env.REDIS_URL),g.debug("[conversationMemoryFactory] Redis configuration normalized",{host:r.host||"localhost",port:r.port||6379,hasPassword:!!r.password,db:r.db||0,keyPrefix:r.keyPrefix||"neurolink:conversation:",ttl:r.ttl||86400,hasConnectionOptions:!!r.connectionOptions}),r}var Y1e=A(async()=>{"use strict";Q();YY();await J1e()});var Q1e={};le(Q1e,{initializeConversationMemory:()=>ltr});async function ltr(r){if(g.debug("[conversationMemoryInitializer] Initialize conversation memory called",{hasConfig:!!r,hasMemoryConfig:!!r?.conversationMemory,memoryEnabled:r?.conversationMemory?.enabled||!1,storageType:process.env.STORAGE_TYPE||"memory"}),!r?.conversationMemory?.enabled)return g.debug("[conversationMemoryInitializer] Conversation memory not enabled - skipping initialization"),null;try{g.debug("[conversationMemoryInitializer] Applying conversation memory defaults");let e=nMe(r.conversationMemory);g.debug("[conversationMemoryInitializer] Memory configuration processed",{enabled:e.enabled,maxSessions:e.maxSessions,maxTurnsPerSession:e.maxTurnsPerSession,enableSummarization:e.enableSummarization});let t=!!r.conversationMemory?.redisConfig,n=t?"redis":Z1e();if(g.debug("[conversationMemoryInitializer] Storage type determined",{storageType:n,fromConfig:t,fromEnv:!t&&!!process.env.STORAGE_TYPE}),n==="redis"){g.info("[conversationMemoryInitializer] Initializing Redis-based conversation memory manager"),g.debug("[conversationMemoryInitializer] Getting Redis configuration");let o=r.conversationMemory?.redisConfig||X1e(),s=r.conversationMemory?.redisConfig?"SDK input (from Lighthouse)":"environment variables (NeuroLink)";g.debug("[conversationMemoryInitializer] Redis configuration retrieved",{configSource:s,host:o.host||"localhost",port:o.port||6379,hasPassword:!!o.password,db:o.db||0,keyPrefix:o.keyPrefix||"neurolink:conversation:",ttl:o.ttl||86400}),g.debug("[conversationMemoryInitializer] Creating Redis conversation memory manager");let i=Nte(e,"redis",o);return g.debug("[conversationMemoryInitializer] Checking Redis manager creation result",{managerType:i?.constructor?.name||"unknown",isRedisType:i?.constructor?.name==="RedisConversationMemoryManager",hasConfig:!!i?.config}),g.info("[conversationMemoryInitializer] Redis conversation memory manager created successfully"),i?.constructor?.name!=="RedisConversationMemoryManager"&&g.warn("[conversationMemoryInitializer] Created manager is not of RedisConversationMemoryManager type",{actualType:i?.constructor?.name}),i}else{g.info("[conversationMemoryInitializer] Initializing in-memory conversation memory manager"),g.debug("[conversationMemoryInitializer] Creating in-memory conversation memory manager");let o=Nte(e);return g.debug("[conversationMemoryInitializer] Checking memory manager creation result",{managerType:o?.constructor?.name||"unknown",isInMemoryType:o?.constructor?.name==="ConversationMemoryManager",hasConfig:!!o?.config}),g.info("[conversationMemoryInitializer] In-memory conversation memory manager created successfully",{maxSessions:e.maxSessions,maxTurnsPerSession:e.maxTurnsPerSession,managerType:o?.constructor?.name}),o}}catch(e){throw g.error("[conversationMemoryInitializer] Failed to initialize conversation memory",{error:e instanceof Error?e.message:String(e),errorName:e instanceof Error?e.name:"UnknownError",errorStack:e instanceof Error?e.stack:void 0,storageType:process.env.STORAGE_TYPE||"memory",memoryConfig:{enabled:r?.conversationMemory?.enabled,maxSessions:r?.conversationMemory?.maxSessions,maxTurnsPerSession:r?.conversationMemory?.maxTurnsPerSession},redisConfig:{host:process.env.REDIS_HOST||"(not set)",port:process.env.REDIS_PORT||"(not set)",hasPassword:!!process.env.REDIS_PASSWORD,keyPrefix:process.env.REDIS_KEY_PREFIX||"(not set)"}}),process.env.STORAGE_TYPE==="redis"&&g.error("[conversationMemoryInitializer] Redis configuration error details",{REDIS_HOST:process.env.REDIS_HOST||"(not set)",REDIS_PORT:process.env.REDIS_PORT||"(not set)",REDIS_PASSWORD:process.env.REDIS_PASSWORD?"******":"(not set)",REDIS_DB:process.env.REDIS_DB||"(not set)",REDIS_KEY_PREFIX:process.env.REDIS_KEY_PREFIX||"(not set)",REDIS_TTL:process.env.REDIS_TTL||"(not set)",errorMessage:e instanceof Error?e.message:String(e)}),e}}var eFe=A(async()=>{"use strict";pv();Q();await Y1e()});var tFe={};le(tFe,{AuthProviderFactory:()=>Ao,createAuthProvider:()=>Dte});async function Dte(r,e){return Ao.createProvider(r,e)}var Ao,KA=A(()=>{"use strict";Q();Ci();Ao=class r{static providers=new Map;static aliasMap=new Map;static registerProvider(e,t,n=[],o){r.providers.set(e,{factory:t,aliases:n,metadata:o});for(let s of n)r.aliasMap.set(s.toLowerCase(),e);g.debug(`Registered auth provider: ${e}`)}static async createProvider(e,t){let n=r.resolveType(e),o=r.providers.get(n);if(!o)throw Qe.create("PROVIDER_NOT_FOUND",`Auth provider not found: ${e}. Available: ${r.getAvailableProviders().join(", ")}`);try{return await o.factory(t)}catch(s){throw Qe.create("CREATION_FAILED",`Failed to create auth provider ${e}: ${s instanceof Error?s.message:String(s)}`,{cause:s instanceof Error?s:void 0})}}static hasProvider(e){return r.providers.has(e)||r.aliasMap.has(e.toLowerCase())}static getAvailableProviders(){return Array.from(r.providers.keys())}static getProviderMetadata(e){let t=r.resolveType(e);return r.providers.get(t)?.metadata}static getAllProviderInfo(){return Array.from(r.providers.entries()).map(([e,t])=>({type:e,aliases:t.aliases,metadata:t.metadata}))}static clearRegistrations(){r.providers.clear(),r.aliasMap.clear()}static resolveType(e){return r.aliasMap.get(e.toLowerCase())||e}}});var oMe={};le(oMe,{NeuroLink:()=>Fv,default:()=>ptr,neurolink:()=>nFe});function utr(r){let e=r.toLowerCase();return e.includes("not found")||e.includes("404")||e.includes("does not exist")||e.includes("no such")?"not_found":e.includes("permission")||e.includes("forbidden")||e.includes("403")||e.includes("unauthorized")||e.includes("401")||e.includes("access denied")?"permission_denied":e.includes("timeout")||e.includes("timed out")||e.includes("deadline exceeded")?"timeout":e.includes("rate limit")||e.includes("429")||e.includes("too many requests")||e.includes("throttl")?"rate_limited":e.includes("invalid")||e.includes("validation")||e.includes("bad request")||e.includes("400")?"validation_error":"unknown"}function dtr(r){switch(r){case"not_found":return"validation";case"permission_denied":return"permission";case"timeout":return"timeout";case"rate_limited":return"resource";case"validation_error":return"validation";case"unknown":return"execution"}}function rFe(r){if(r instanceof Hc||r instanceof kn||r instanceof wD)return!0;if(r&&typeof r=="object"){let e=r,t=typeof e.status=="number"?e.status:typeof e.statusCode=="number"?e.statusCode:void 0;if(t&&VDe.includes(t))return!0}if(r instanceof Error){let e=r.message;if(e.includes("NOT_FOUND")||e.includes("Model Not Found")||e.includes("model not found")||e.includes("PERMISSION_DENIED")||e.includes("UNAUTHENTICATED"))return!0}return!1}var Lte,Fv,nFe,ptr,sz=A(async()=>{"use strict";Kt();X0();xs();aR();$ge();qPe();aMe();cMe();pMe();mMe();fMe();Id();YY();Gc();O1();YC();TMe();wMe();EMe();n7();i7();yz();$Q();BQ();NNe();qQ();UNe();JS();sB();jNe();GNe();AD();vr();GC();wm();TDe();wDe();yL();tr();pv();bt();PDe();Q();C$();rz();MDe();qDe();Im();GDe();Zp();cee();RL();Hy();mee();PB();try{process.env.DOTENV_CONFIG_QUIET=process.env.DOTENV_CONFIG_QUIET??"true";let{config:r}=await Promise.resolve().then(()=>la(PLe(),1));r({quiet:!0})}catch{}Lte=new Zy,Fv=class{mcpInitialized=!1;mcpSkipped=!1;mcpInitPromise=null;emitter=new _r;_taskManager;_taskManagerConfig;toolRegistry;autoDiscoveredServerInfos=[];externalServerManager;toolCache=null;toolCacheDuration;modelAliasConfig;lastCompactionMessageCount=new Map;getCompactionSessionId(e){return e.context?.sessionId||"__default__"}mcpToolResultCache;mcpToolRouter;mcpToolBatcher;mcpEnhancedDiscovery;mcpToolMiddlewares=[];mcpArtifactStore;_disableToolCacheForCurrentRequest=!1;mcpEnhancementsConfig;toolCircuitBreakers=new Map;toolExecutionMetrics=new Map;currentStreamToolExecutions=[];toolExecutionHistory=[];activeToolExecutions=new Map;emitToolEndEvent(e,t,n,o,s){this.emitter.emit("tool:end",em(e,{responseTime:Date.now()-t,success:n,timestamp:Date.now(),result:o,error:s?s.message:void 0}))}conversationMemory;conversationMemoryNeedsInit=!1;conversationMemoryConfig;enableOrchestration;authProvider;pendingAuthConfig;authInitPromise;credentials;resolveCredentials(e){if(!this.credentials&&!e)return;if(!this.credentials)return e;if(!e)return this.credentials;let t={...this.credentials};for(let n of Object.keys(e)){let o=this.credentials[n],s=e[n];o&&s&&typeof o=="object"&&typeof s=="object"?t[n]={...o,...s}:t[n]=s??o}return t}hitlManager;_sessionCostUsd=0;fileRegistry;cachedFileTools=null;memoryInstance;memorySDKConfig;async setLangfuseContextFromOptions(e,t){if(e.context&&typeof e.context=="object"&&e.context!==null){let n=!1;try{let o=e.context;if(o.userId||o.sessionId||o.conversationId||o.requestId||o.traceName||o.metadata){let s;if(o.metadata&&typeof o.metadata=="object"){let i=o.metadata,a={};for(let[l,u]of Object.entries(i))(typeof u=="string"||typeof u=="number"||typeof u=="boolean")&&(a[l]=u);Object.keys(a).length>0&&(s=a)}return await new Promise((i,a)=>{Yy({userId:typeof o.userId=="string"?o.userId:null,sessionId:typeof o.sessionId=="string"?o.sessionId:null,conversationId:typeof o.conversationId=="string"?o.conversationId:null,requestId:typeof o.requestId=="string"?o.requestId:null,traceName:typeof o.traceName=="string"?o.traceName:null,metadata:o.metadata&&typeof o.metadata=="object"?o.metadata:null,...s!==void 0&&{customAttributes:s}},async()=>{try{n=!0;let l=await t();i(l)}catch(l){a(l)}})})}}catch(o){if(n)throw o;g.warn("Failed to set Langfuse context from options",{error:o instanceof Error?o.message:String(o)})}}return await t()}createMetricsTraceContext(){let e=ct.getSpan(Tr.active());if(e){let t=e.spanContext();if(t.traceId&&t.traceId!=="00000000000000000000000000000000")return{traceId:t.traceId,parentSpanId:t.spanId}}return{traceId:crypto.randomUUID().replace(/-/g,""),parentSpanId:crypto.randomUUID().replace(/-/g,"").substring(0,16)}}enforceSessionBudget(e){if(!(e===void 0||e<=0||this._sessionCostUsd<e))throw new Je({code:"SESSION_BUDGET_EXCEEDED",message:`Session budget exceeded: spent $${this._sessionCostUsd.toFixed(4)} of $${e.toFixed(4)} limit`,category:"validation",severity:"high",retriable:!1,context:{spent:this._sessionCostUsd,limit:e}})}assertInputText(e,t){if(!e||typeof e!="string")throw new Error(t)}async applyAuthenticatedRequestContext(e){if(e.auth?.token){let{AuthError:n}=await Promise.resolve().then(()=>(Ci(),RNe));if(await this.ensureAuthProvider(),!this.authProvider)throw n.create("PROVIDER_ERROR","No auth provider configured. Set auth in constructor or via setAuthProvider() before using auth: { token }.");let o;try{o=await Oe(this.authProvider.authenticateToken(e.auth.token),5e3,n.create("PROVIDER_ERROR","Auth token validation timed out after 5000ms"))}catch(s){throw s instanceof Error&&"feature"in s&&s.feature==="Auth"?s:n.create("PROVIDER_ERROR",`Auth token validation failed: ${s instanceof Error?s.message:String(s)}`)}if(!o.valid)throw n.create("INVALID_TOKEN",o.error||"Token validation failed");if(!o.user)throw n.create("INVALID_TOKEN","Token validated but no user identity returned");if(!o.user.id)throw n.create("INVALID_TOKEN","Token validated but user identity missing required 'id' field");e.context={...e.context||{},userId:o.user.id,userEmail:o.user.email,userRoles:o.user.roles}}if(!e.requestContext)return;let t=e.auth?.token&&this.authProvider?{userId:e.context?.userId,userEmail:e.context?.userEmail,userRoles:e.context?.userRoles}:{};e.context={...e.context||{},...e.requestContext,...t}}applyGenerateLifecycleMiddleware(e){!e.onFinish&&!e.onError||(e.middleware={...e.middleware,middlewareConfig:{...e.middleware?.middlewareConfig,lifecycle:{...e.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...e.middleware?.middlewareConfig?.lifecycle?.config,...e.onFinish!==void 0?{onFinish:e.onFinish}:{},...e.onError!==void 0?{onError:e.onError}:{}}}}})}applyStreamLifecycleMiddleware(e){!e.onFinish&&!e.onError&&!e.onChunk||(e.middleware={...e.middleware,middlewareConfig:{...e.middleware?.middlewareConfig,lifecycle:{...e.middleware?.middlewareConfig?.lifecycle,enabled:!0,config:{...e.middleware?.middlewareConfig?.lifecycle?.config,...e.onFinish!==void 0?{onFinish:e.onFinish}:{},...e.onError!==void 0?{onError:e.onError}:{},...e.onChunk!==void 0?{onChunk:e.onChunk}:{}}}}})}initializeMemoryConfig(){let e=this.conversationMemoryConfig?.conversationMemory?.memory;return e?.enabled?(this.memorySDKConfig=e,!0):!1}ensureMemoryReady(){return this.memoryInstance!==void 0?this.memoryInstance:this.initializeMemoryConfig()?this.memorySDKConfig?(this.memoryInstance=BNe(this.memorySDKConfig),this.memoryInstance):(this.memoryInstance=null,null):(this.memoryInstance=null,null)}toolExecutionContext;observabilityConfig;metricsAggregator=new Hh;get _metricsTraceContext(){return Lte.getStore()??null}constructor(e){this.toolRegistry=e?.toolRegistry||new Av,this.fileRegistry=new uz,this.observabilityConfig=e?.observability,this.enableOrchestration=e?.enableOrchestration??!1,e?.modelAliasConfig&&(this.modelAliasConfig=e.modelAliasConfig),g.setEventEmitter(this.emitter);let t=process.env.NEUROLINK_TOOL_CACHE_DURATION;this.toolCacheDuration=t?parseInt(t,10):2e4;let n=Date.now(),o=process.hrtime.bigint(),s=`neurolink-constructor-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;this.initializeProviderRegistry(s,n,o),this.initializeConversationMemory(e,s,n,o),this.initializeExternalServerManager(s,n,o),this.initializeHITL(e,s,n,o),this.initializeMCPEnhancements(e),this.registerFileTools(),this.registerMemoryRetrievalTools(),this.initializeLangfuse(s,n,o),this.initializeMetricsListeners(),this.logConstructorComplete(s,n,o),e?.auth&&(this.pendingAuthConfig=e.auth),e?.credentials&&(this.credentials=e.credentials),this._taskManagerConfig=e?.tasks,this._taskManagerConfig&&(this._taskManager=new IA(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerTaskTools(this._taskManager))}get tasks(){return this._taskManager||(this._taskManager=new IA(this,this._taskManagerConfig),this._taskManager.setEmitter(this.emitter),this.registerTaskTools(this._taskManager)),this._taskManager}initializeProviderRegistry(e,t,n){let o=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F3D7}\uFE0F LOG_POINT_C002_PROVIDER_REGISTRY_SETUP_START",{logPoint:"C002_PROVIDER_REGISTRY_SETUP_START",constructorId:e,timestamp:new Date().toISOString(),elapsedMs:Date.now()-t,elapsedNs:(process.hrtime.bigint()-n).toString(),registrySetupStartTimeNs:o.toString(),message:"Starting ProviderRegistry configuration for security"}),_u.setOptions({enableManualMCP:!1})}initializeConversationMemory(e,t,n,o){if(e?.conversationMemory?.enabled){let s=process.hrtime.bigint();this.conversationMemoryConfig=e,this.conversationMemoryNeedsInit=!0;let a=process.hrtime.bigint()-s;g.debug("[NeuroLink] \u2705 LOG_POINT_C006_MEMORY_INIT_FLAG_SET_SUCCESS",{logPoint:"C006_MEMORY_INIT_FLAG_SET_SUCCESS",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),memoryInitDurationNs:a.toString(),memoryInitDurationMs:Number(a)/Su,message:"Conversation memory initialization flag set successfully for lazy loading"})}else g.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C008_MEMORY_DISABLED",{logPoint:"C008_MEMORY_DISABLED",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!e,hasMemoryConfig:!!e?.conversationMemory,memoryEnabled:e?.conversationMemory?.enabled||!1,reason:e?e.conversationMemory?e.conversationMemory.enabled?"UNKNOWN":"MEMORY_DISABLED":"NO_MEMORY_CONFIG":"NO_CONFIG",message:"Conversation memory not enabled - skipping initialization"})}initializeHITL(e,t,n,o){if(e?.hitl?.enabled){let s=process.hrtime.bigint();g.debug("[NeuroLink] \u{1F6E1}\uFE0F LOG_POINT_C015_HITL_INIT_START",{logPoint:"C015_HITL_INIT_START",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitStartTimeNs:s.toString(),hitlConfig:{enabled:e.hitl.enabled,dangerousActions:e.hitl.dangerousActions||[],timeout:e.hitl.timeout||3e4,allowArgumentModification:e.hitl.allowArgumentModification??!0,auditLogging:e.hitl.auditLogging??!1},message:"Starting HITL (Human-in-the-Loop) initialization"});try{this.hitlManager=new pz(e.hitl),this.toolRegistry.setHITLManager(this.hitlManager),this.externalServerManager.setHITLManager(this.hitlManager),this.setupHITLEventForwarding();let a=process.hrtime.bigint()-s;g.debug("[NeuroLink] \u2705 LOG_POINT_C016_HITL_INIT_SUCCESS",{logPoint:"C016_HITL_INIT_SUCCESS",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:a.toString(),hitlInitDurationMs:Number(a)/Su,hasHitlManager:!!this.hitlManager,message:"HITL (Human-in-the-Loop) initialized successfully"}),g.info("[NeuroLink] HITL safety features enabled",{dangerousActions:e.hitl.dangerousActions?.length||0,timeout:e.hitl.timeout||3e4,allowArgumentModification:e.hitl.allowArgumentModification??!0,auditLogging:e.hitl.auditLogging??!1})}catch(i){let l=process.hrtime.bigint()-s;throw g.error("[NeuroLink] \u274C LOG_POINT_C017_HITL_INIT_ERROR",{logPoint:"C017_HITL_INIT_ERROR",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hitlInitDurationNs:l.toString(),hitlInitDurationMs:Number(l)/Su,error:i instanceof Error?i.message:String(i),errorName:i instanceof Error?i.name:"UnknownError",errorStack:i instanceof Error?i.stack:void 0,message:"HITL (Human-in-the-Loop) initialization failed"}),i}}else g.debug("[NeuroLink] \u{1F6AB} LOG_POINT_C018_HITL_DISABLED",{logPoint:"C018_HITL_DISABLED",constructorId:t,timestamp:new Date().toISOString(),elapsedMs:Date.now()-n,elapsedNs:(process.hrtime.bigint()-o).toString(),hasConfig:!!e,hasHitlConfig:!!e?.hitl,hitlEnabled:e?.hitl?.enabled||!1,reason:e?e.hitl?e.hitl.enabled?"UNKNOWN":"HITL_DISABLED":"NO_HITL_CONFIG":"NO_CONFIG",message:"HITL (Human-in-the-Loop) not enabled - skipping initialization"})}initializeMCPEnhancements(e){let t=e?.mcp;if(this.mcpEnhancementsConfig=t,t?.cache?.enabled!==!1&&(this.mcpToolResultCache=new Ag({ttl:t?.cache?.ttl??3e5,maxSize:t?.cache?.maxSize??500,strategy:t?.cache?.strategy??"lru"}),g.debug("[NeuroLink] MCP tool result cache initialized",{ttl:t?.cache?.ttl??3e5,maxSize:t?.cache?.maxSize??500,strategy:t?.cache?.strategy??"lru"})),t?.batcher?.enabled&&(this.mcpToolBatcher=new Rg({maxBatchSize:t.batcher.maxBatchSize??10,maxWaitMs:t.batcher.maxWaitMs??100}),this.mcpToolBatcher.setToolExecutor(async(n,o)=>this.executeToolInternal(n,o,{timeout:Rl.EXECUTION_DEFAULT_MS,maxRetries:Qn.DEFAULT,retryDelayMs:mn.BASE_MS})),g.debug("[NeuroLink] MCP tool call batcher initialized")),t?.discovery?.enabled!==!1&&(this.mcpEnhancedDiscovery=new yv,g.debug("[NeuroLink] Enhanced tool discovery initialized")),t?.middleware?.length&&(this.mcpToolMiddlewares=[...t.middleware],g.debug("[NeuroLink] MCP tool middlewares registered",{count:this.mcpToolMiddlewares.length})),t?.outputLimits){let n=t.outputLimits.strategy??"externalize",o=t.outputLimits.maxBytes??PNe,s=t.outputLimits.warnBytes??zQ,i;n==="externalize"&&(i=new cB,this.mcpArtifactStore=i,g.debug("[NeuroLink] MCP artifact store initialized (local-temp)"));let a=new aB({strategy:n,maxBytes:o,warnBytes:s},i);this.externalServerManager.setOutputNormalizer(a),g.debug("[NeuroLink] MCP output normalizer initialized",{strategy:n,maxBytes:o,warnBytes:s})}}registerFileTools(){let e=e7(this.fileRegistry),t=Object.entries(e).map(async([n,o])=>{let s=`direct.${n}`,i={name:n,description:o.description||`File tool: ${n}`,inputSchema:{},serverId:"direct",category:"built-in"};await this.toolRegistry.registerTool(s,i,{execute:async a=>{try{return{success:!0,data:await o.execute(a,{toolCallId:"file-tool",messages:[]}),metadata:{toolName:n,serverId:"direct",executionTime:0}}}catch(l){return{success:!1,error:l instanceof Error?l.message:String(l),metadata:{toolName:n,serverId:"direct",executionTime:0}}}},description:o.description,inputSchema:{}})});Promise.all(t).then(()=>{g.debug(`[NeuroLink] Registered ${Object.keys(e).length} file reference tools`)})}registerTaskTools(e){let t=SDe(e);for(let[n,o]of Object.entries(t)){let s=`direct.${n}`,i={name:n,description:o.description||`Task tool: ${n}`,inputSchema:{},serverId:"direct",category:"built-in"};this.toolRegistry.registerTool(s,i,{execute:async a=>{try{return{success:!0,data:await o.execute(a,{toolCallId:"task-tool",messages:[]}),metadata:{toolName:n,serverId:"direct",executionTime:0}}}catch(l){return{success:!1,error:l instanceof Error?l.message:String(l),metadata:{toolName:n,serverId:"direct",executionTime:0}}}},description:o.description,inputSchema:{}})}g.debug(`[NeuroLink] Registered ${Object.keys(t).length} task tools`)}registerMemoryRetrievalTools(){let e=this.conversationMemoryConfig?.conversationMemory,t=!!e?.redisConfig||e&&"redis"in e&&!!e.redis||process.env.STORAGE_TYPE==="redis",n=!!this.mcpArtifactStore;if((!e?.enabled||!t)&&!n){g.debug("[NeuroLink] Skipping memory retrieval tools \u2014 requires Redis conversation memory or an artifact store");return}let s=WQ(void 0,this.mcpArtifactStore).retrieve_context;this.registerTool("retrieve_context",{name:"retrieve_context",description:s.description??"Retrieve context or artifacts",inputSchema:s.inputSchema,execute:async i=>{let a=this.conversationMemory,l=WQ(a,this.mcpArtifactStore);return await Oe(l.retrieve_context.execute(i,{toolCallId:"memory-retrieval",messages:[]}),Rl.EXECUTION_DEFAULT_MS,pe.toolTimeout("retrieve_context",Rl.EXECUTION_DEFAULT_MS))}}),g.info("[NeuroLink] Memory retrieval tools registered")}formatMemoryContext(e,t){return`Context from previous conversations:
|
|
2175
2175
|
|
|
@@ -936,12 +936,16 @@ export class RedisConversationMemoryManager {
|
|
|
936
936
|
const titleGenerator = new NeuroLink({
|
|
937
937
|
conversationMemory: { enabled: false },
|
|
938
938
|
});
|
|
939
|
-
const
|
|
939
|
+
const defaultTitlePrompt = `Generate a clear, concise, and descriptive title (20-25 letters maximum) for a conversation based on the following user message.
|
|
940
940
|
The title must meaningfully reflect the topic or intent of the message.
|
|
941
941
|
Do not output anything unrelated, vague, or generic.
|
|
942
942
|
Do not say you cannot create a title. Always return a valid title.
|
|
943
943
|
|
|
944
944
|
User message: "${userMessage}"`;
|
|
945
|
+
const customPrompt = process.env.NEUROLINK_TITLE_PROMPT;
|
|
946
|
+
const titlePrompt = customPrompt
|
|
947
|
+
? customPrompt.replace(/\$\{userMessage\}/g, userMessage)
|
|
948
|
+
: defaultTitlePrompt;
|
|
945
949
|
const result = await titleGenerator.generate({
|
|
946
950
|
input: { text: titlePrompt },
|
|
947
951
|
provider: this.config.summarizationProvider || "vertex",
|
|
@@ -936,12 +936,16 @@ export class RedisConversationMemoryManager {
|
|
|
936
936
|
const titleGenerator = new NeuroLink({
|
|
937
937
|
conversationMemory: { enabled: false },
|
|
938
938
|
});
|
|
939
|
-
const
|
|
939
|
+
const defaultTitlePrompt = `Generate a clear, concise, and descriptive title (20-25 letters maximum) for a conversation based on the following user message.
|
|
940
940
|
The title must meaningfully reflect the topic or intent of the message.
|
|
941
941
|
Do not output anything unrelated, vague, or generic.
|
|
942
942
|
Do not say you cannot create a title. Always return a valid title.
|
|
943
943
|
|
|
944
944
|
User message: "${userMessage}"`;
|
|
945
|
+
const customPrompt = process.env.NEUROLINK_TITLE_PROMPT;
|
|
946
|
+
const titlePrompt = customPrompt
|
|
947
|
+
? customPrompt.replace(/\$\{userMessage\}/g, userMessage)
|
|
948
|
+
: defaultTitlePrompt;
|
|
945
949
|
const result = await titleGenerator.generate({
|
|
946
950
|
input: { text: titlePrompt },
|
|
947
951
|
provider: this.config.summarizationProvider || "vertex",
|
|
@@ -397,6 +397,9 @@ function toModelMessage(message) {
|
|
|
397
397
|
if (message.role === "user" ||
|
|
398
398
|
message.role === "assistant" ||
|
|
399
399
|
message.role === "system") {
|
|
400
|
+
if (message.content.trim() === "") {
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
400
403
|
return {
|
|
401
404
|
role: message.role,
|
|
402
405
|
content: message.content,
|
|
@@ -397,6 +397,9 @@ function toModelMessage(message) {
|
|
|
397
397
|
if (message.role === "user" ||
|
|
398
398
|
message.role === "assistant" ||
|
|
399
399
|
message.role === "system") {
|
|
400
|
+
if (message.content.trim() === "") {
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
400
403
|
return {
|
|
401
404
|
role: message.role,
|
|
402
405
|
content: message.content,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@juspay/neurolink",
|
|
3
|
-
"version": "9.56.
|
|
3
|
+
"version": "9.56.1",
|
|
4
4
|
"packageManager": "pnpm@10.15.1",
|
|
5
5
|
"description": "Universal AI Development Platform with working MCP integration, multi-provider support, and professional CLI. Built-in tools operational, 58+ external MCP servers discoverable. Connect to filesystem, GitHub, database operations, and more. Build, test, and deploy AI applications with 13 providers: OpenAI, Anthropic, Google AI, AWS Bedrock, Azure, Hugging Face, Ollama, and Mistral AI.",
|
|
6
6
|
"author": {
|