@juspay/neurolink 13.8.1 → 13.8.3

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 CHANGED
@@ -1,9 +1,8 @@
1
- ## [13.8.1](https://github.com/juspay/neurolink/compare/v13.8.0...v13.8.1) (2026-10-22)
1
+ ## [13.8.3](https://github.com/juspay/neurolink/compare/v13.8.2...v13.8.3) (2026-10-23)
2
2
 
3
3
  ### Bug Fixes
4
4
 
5
- - **(mcp):** stop stdio servers that are still starting when the host exits ([dd78363](https://github.com/juspay/neurolink/commit/dd78363ae8df7cd340ea0422a0844533592bd336))
6
- - **(stream):** skip MCP initialization when a stream disables tools ([37b914e](https://github.com/juspay/neurolink/commit/37b914e5d96de64ec8298cd9232fbf23d84496d9))
5
+ - **(deps):** clear the docs-site dompurify critical advisory ([39af0f7](https://github.com/juspay/neurolink/commit/39af0f74d6613aff8871d3ed150d73c963d8b5c2))
7
6
 
8
7
  ## [11.2.3](https://github.com/juspay/neurolink/compare/v11.2.2...v11.2.3) (2026-08-19)
9
8
 
@@ -1891,7 +1891,7 @@ For "closing" slides (shows checkmarks \u2713):
1891
1891
  - For summary/thank you \u2192 type="closing" (checkmarks \u2713)
1892
1892
  - For regular content \u2192 type="content" (disc bullets \u2022)
1893
1893
 
1894
- \u26A0\uFE0F CRITICAL: Content MUST fit within slide box. Keep text SHORT.`,ccr=5,ucr=50,dcr=10,pcr=5e3,mcr=Object.keys(LC),hcr=["business","students","technical","general"],fcr=["professional","casual","educational","persuasive"],gcr=["16:9","4:3"],M$={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}},que=6e4,P$=3e4,jue=5,xc=3e5}}),gu,Ll,Vue=S({"src/lib/features/ppt/pptError.ts"(){"use strict";et(),gu={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"},Ll=class extends Me{constructor(e,t,r,n){super({code:t,message:e,category:"execution",severity:"high",retriable:!1,context:{...r,originalMessage:n?.message},originalError:n}),this.name="PPTError"}}}}),ycr={};ce(ycr,{PPT_VALID_PROVIDERS:()=>_T,bufferToDataUrl:()=>FC,calculateFontSize:()=>kcr,createFormattedTextProps:()=>TT,ensureOutputDirectory:()=>wcr,extractPPTContext:()=>l0n,generateOutputPath:()=>vcr,getEffectivePPTProvider:()=>c0n,getFailureStage:()=>Hue,getLayoutName:()=>Ecr,hasMarkdownFormatting:()=>bT,isLogoConfig:()=>Tcr,isObject:()=>bcr,normalizeLogoConfig:()=>_cr,parseMarkdownText:()=>wT,toError:()=>Scr,validateImageBuffer:()=>Wue});function l0n(e){const t=e.output?.ppt;if(!t)throw new Ll("PPT options are required when mode is 'ppt'",gu.INVALID_INPUT,{field:"output.ppt"});let r;if(t.logoPath){if(Buffer.isBuffer(t.logoPath)||typeof t.logoPath=="string")r=t.logoPath;else if(typeof t.logoPath=="object"&&"data"in t.logoPath){const o=t.logoPath.data;r=Buffer.isBuffer(o)||typeof o=="string"?o:void 0}}const n=[];if(e.input?.images){for(const o of e.input.images)if(Buffer.isBuffer(o)||typeof o=="string")n.push(o);else if(typeof o=="object"&&"data"in o){const i=o.data;(Buffer.isBuffer(i)||typeof i=="string")&&n.push(i)}}return!r&&n.length>0&&(r=n[0]),{topic:e.input?.text||"",pages:t.pages,theme:t.theme??"AI will decide",audience:t.audience??"AI will decide",tone:t.tone??"AI will decide",generateAIImages:t.generateAIImages??!1,aspectRatio:t.aspectRatio||"16:9",outputPath:t.outputPath,logo:r,images:n.length>0?n:void 0,provider:e.provider,model:e.model}}async function c0n(e,t,r,n){const{ErrorFactory:o}=await Promise.resolve().then(()=>(et(),AS)),i=t.toLowerCase();if(_T.includes(i)){const s=e,a=r||s?.modelName||s?.getDefaultModel?.()||"";return h.debug("[PPT Utils] Current provider is valid for PPT",{provider:t,model:a}),{provider:e,providerName:t,modelName:a,wasAutoSelected:!1}}h.info("[PPT Utils] Current provider not valid for PPT, auto-selecting",{currentProvider:t});for(const s of _T)if(qce(s)){h.info("[PPT Utils] Auto-selected PPT provider",{originalProvider:t,selectedProvider:s});const{AIProviderFactory:a}=await Promise.resolve().then(()=>(Qa(),xI)),{withTimeout:l}=await Promise.resolve().then(()=>(et(),AS)),{PPT_GENERATION_TIMEOUT_MS:c}=await Promise.resolve().then(()=>(vT(),Uue)),u=await l(a.createProvider(s,void 0,!0,n),c/4,o.toolTimeout("createProvider",c/4));return{provider:u,providerName:s,modelName:u.modelName,wasAutoSelected:!0}}throw o.invalidParameters("ppt-generation",new Error(`No PPT-compatible provider available. Configure one of: ${_T.join(", ")}`),{currentProvider:t,validProviders:_T})}function vcr(e){const t=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19),n=`${e.topic.substring(0,30).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase()}_${t}.pptx`;return e.outputPath?e.outputPath.endsWith(".pptx")?e.outputPath:Mt(e.outputPath,n):Mt(process.cwd(),"output",n)}async function wcr(e){const t=I7(e);try{const{withTimeout:r,ErrorFactory:n}=await Promise.resolve().then(()=>(et(),AS)),{PPT_GENERATION_TIMEOUT_MS:o}=await Promise.resolve().then(()=>(vT(),Uue));await r(rZ(t,{recursive:!0}),o/8,n.toolTimeout("mkdirOutputDirectory",o/8))}catch(r){const n=r instanceof Error?r:new Error(String(r));throw new Ll(`Failed to create output directory: ${t}`,gu.FILE_WRITE_FAILED,{directory:t},n)}}function bcr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Tcr(e){return bcr(e)?"data"in e&&(Buffer.isBuffer(e.data)||typeof e.data=="string"):!1}function _cr(e){return e===null?null:Buffer.isBuffer(e)||typeof e=="string"?{data:e,position:"bottom-right",width:1,height:.4,showOn:"all-slides"}:Tcr(e)?e:null}function Ecr(e){switch(e){case"16:9":return"LAYOUT_16x9";case"4:3":return"LAYOUT_4x3";default:return"LAYOUT_16x9"}}function Scr(e){return e instanceof Error?e:new Error(String(e))}function Hue(e){return e.contentPlan===null?"content-planning":e.slides===null?"slide-generation":e.outputPath===null?"pptx-assembly":"file-output"}function Wue(e){return!e||e.length===0?{isValid:!1,mimeType:"",format:"",error:"Empty or undefined buffer"}:e.length<100?{isValid:!1,mimeType:"",format:"",error:`Buffer too small (${e.length} bytes)`}:e[0]===255&&e[1]===216&&e[2]===255?{isValid:!0,mimeType:"image/jpeg",format:"JPEG"}:e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?{isValid:!0,mimeType:"image/png",format:"PNG"}:e[0]===71&&e[1]===73&&e[2]===70?{isValid:!0,mimeType:"image/gif",format:"GIF"}:e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e.length>12&&e.slice(8,12).toString()==="WEBP"?{isValid:!0,mimeType:"image/webp",format:"WebP"}:e[0]===66&&e[1]===77?{isValid:!0,mimeType:"image/bmp",format:"BMP"}:{isValid:!1,mimeType:"image/png",format:"unknown",error:`Unknown format (magic bytes: ${e.slice(0,4).toString("hex")})`}}function FC(e){const t=Wue(e);return!t.isValid&&t.format===""?(h.warn("[bufferToDataUrl] Invalid image buffer",{error:t.error}),null):`data:${t.mimeType||"image/png"};base64,${e.toString("base64")}`}function wT(e){if(!e||typeof e!="string")return[{text:e||""}];const t=[],r=/(\*\*\*(.+?)\*\*\*|\*\*(.+?)\*\*|\*(.+?)\*)/g;let n=0;for(;;){const o=r.exec(e);if(o===null)break;o.index>n&&t.push({text:e.slice(n,o.index)}),o[2]?t.push({text:o[2],bold:!0,italic:!0}):o[3]?t.push({text:o[3],bold:!0}):o[4]&&t.push({text:o[4],italic:!0}),n=r.lastIndex}return n<e.length&&t.push({text:e.slice(n)}),t.length===0&&t.push({text:e}),t}function bT(e){return!e||typeof e!="string"?!1:/\*{1,3}[^*]+\*{1,3}/.test(e)}function TT(e,t){return e.map(r=>({text:r.text,options:{fontSize:t.fontSize,fontFace:t.fontFace,color:t.color,bold:r.bold||t.baseBold||!1,italic:r.italic||!1}}))}function kcr(e,t=18){return e<=5?t:e<=7?Math.max(12,t-2):e<=10?Math.max(12,t-4):12}var _T,Kue=S({"src/lib/features/ppt/utils.ts"(){"use strict";yi(),Tr(),Gh(),z(),Vue(),_T=["vertex","openai","azure","anthropic","google-ai","bedrock"]}});function u0n(e,t,r=!1){const n=t/72,o=.42,i=r?1.1:1,s=n*o*i;return e.length*s}function Os(e,t,r,n=!0){if(e.addText(t,{x:Gt.title.x,y:Gt.title.y,w:Gt.title.w,h:Gt.title.h,fontSize:r.fonts.sizes.heading,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),bold:!0,fit:Ot}),n){const o=u0n(t,r.fonts.sizes.heading,!0),i=Gt.title.w,a=Math.min(i,Math.max(1,o));e.addShape("rect",{x:Gt.title.x,y:Gt.title.y+Gt.title.h+.1,w:a,h:.03,fill:{color:r.colors.primary.replace("#","")}})}}function xcr(e){const{slide:t,bullets:r,startX:n,startY:o,width:i,theme:s,itemSpacing:a=.45}=e;if(!r||r.length===0)return;const l=Math.max(a,ST*2);r.forEach((c,u)=>{if(!c||!c.text)return;const d=c.bold||c.emphasis||!1,p=c.color?.replace("#","")||s.colors.text.replace("#","");if(bT(c.text)){const m=wT(c.text),f=[{text:"\u2022 ",options:{fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p}},...TT(m,{fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p,baseBold:d})];t.addText(f,{x:n,y:o+u*l,w:i,h:Math.max(.4,l-ST),fit:Ot})}else{const m=`\u2022 ${c.text}`;t.addText(m,{x:n,y:o+u*l,w:i,h:Math.max(.4,l-ST),fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p,bold:d,fit:Ot})}})}function Acr(e,t,r,n,o="content",i){if(!t||t.length===0)return;if(i?.useIndividualBullets){xcr({slide:e,bullets:t,startX:r.x,startY:r.y,width:r.w,theme:n,itemSpacing:i.itemSpacing??.45});return}const s=Wlr(o),a=kcr(t.length,s.baseFontSize||n.fonts.sizes.body),l=[];t.forEach(c=>{if(!c||!c.text)return;const u=c.bulletStyle||s.bulletStyle||"disc",d=c.fontSize||a,p=c.color?.replace("#","")||n.colors.text.replace("#",""),m=c.bold??c.emphasis??!1;let f;if(c.icon?f={code:c.icon}:f=Klr(u),bT(c.text)){const g=wT(c.text),y=TT(g,{fontSize:d,fontFace:n.fonts.body,color:p,baseBold:m});l.push({text:y,options:{bullet:f,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}})}else l.push({text:c.text,options:{bullet:f,fontSize:d,fontFace:n.fonts.body,color:p,bold:m,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}});c.subBullets&&c.subBullets.length>0&&c.subBullets.forEach(g=>{if(bT(g)){const y=wT(g),v=TT(y,{fontSize:Math.max(10,d-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#","")});l.push({text:v,options:{bullet:!0,indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})}else l.push({text:g,options:{bullet:!0,fontSize:Math.max(10,d-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})})}),e.addText(l,{x:r.x,y:r.y,w:r.w,h:r.h,valign:"top",fit:Ot})}function Jue(e,t,r){const n=Wue(t);if(!n.isValid&&n.format===""){h.warn("[addImage] Invalid image buffer",{error:n.error});return}n.isValid||h.warn("[addImage] Image validation warning, attempting to add anyway",{error:n.error,mimeType:n.mimeType});const o=FC(t);if(!o){h.warn("[addImage] Failed to convert buffer to data URL");return}try{e.addImage({data:o,x:r.x,y:r.y,w:r.w,h:r.h,sizing:{type:"cover",w:r.w,h:r.h}})}catch(i){h.error("[addImage] Failed to add image to slide",{error:i instanceof Error?i.message:String(i)})}}function d0n(e){switch(e){case"chart-bar":return"bar";case"chart-line":return"line";case"chart-pie":return"pie";case"chart-area":return"area";default:return"bar"}}function p0n(e,t,r,n,o){const i=r.layoutOptions||{},s=i.title||{},a=i.subtitle||{},l=i.background||{},c=o?FC(o):null;if(c)e.background={data:c},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}});else if(l.color||l.useThemePrimary||l.useThemeSecondary){const m=l.useThemePrimary?n.colors.primary:l.useThemeSecondary?n.colors.secondary:l.color||n.colors.background;e.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:m.replace("#","")}})}const u=o||l.color||l.useThemePrimary||l.useThemeSecondary,d=u?"FFFFFF":n.colors.text.replace("#",""),p=u?"FFFFFF":n.colors.muted.replace("#","");e.addText(t,{x:s.x??.5,y:s.y??2,w:s.w??9,h:s.h??1.2,fontSize:s.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:s.color?.replace("#","")??d,align:s.align??"center",bold:!0,fit:Ot}),r.subtitle&&e.addText(r.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("#","")??p,align:a.align??"center",fit:Ot})}function m0n(e,t,r,n){const o=r.layoutOptions||{},i=o.sectionNumber||{},s=o.title||{},a=o.subtitle||{},l=o.background||{};if(l.color&&e.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:l.color.replace("#","")}}),r.sectionNumber){const c=i.style==="watermark",u=i.style==="small";e.addText(String(r.sectionNumber).padStart(2,"0"),{x:i.x??(c?5.5:.5),y:i.y??(c?.5:1.5),w:c?5:2,h:c?4:1,fontSize:i.fontSize??(c?200:u?32:72),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:c?"right":"left",transparency:c?70:0})}e.addText(t,{x:s.x??.5,y:s.y??2.5,w:s.w??9,h:s.h??1,fontSize:s.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),bold:!0,align:s.align??"left"}),r.subtitle&&e.addText(r.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 h0n(e,t,r,n,o){if(o){const s=FC(o);s&&(e.background={data:s},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}}))}const i=o?"FFFFFF":n.colors.text.replace("#","");if(e.addText(t||"Thank You!",{x:.5,y:1.8,w:9,h:1,fontSize:n.fonts.sizes.title,fontFace:n.fonts.heading,color:i,align:"center",bold:!0,fit:Ot}),r.cta&&e.addText(r.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:Ot}),r.contactInfo){const s=[];if(r.contactInfo.email&&s.push(`Email: ${r.contactInfo.email}`),r.contactInfo.website&&s.push(`Web: ${r.contactInfo.website}`),r.contactInfo.phone&&s.push(`Phone: ${r.contactInfo.phone}`),s.length>0&&e.addText(s.join(" \u2022 "),{x:.5,y:4.2,w:9,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:i,align:"center",fit:Ot}),r.contactInfo.social&&Array.isArray(r.contactInfo.social)&&r.contactInfo.social.length>0){const a=r.contactInfo.social.map(l=>`${l.platform||""}: ${l.handle||""}`).join(" \u2022 ");e.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 Xue(e){const{slide:t,title:r,content:n,layout:o,theme:i,imageBuffer:s,slideType:a="content"}=e;Os(t,r,i);const l=s&&o.includes("image"),c=l?o.includes("left")?Gt.contentRight:Gt.contentLeft:Gt.contentFull;if(n.bullets&&n.bullets.length>0?Acr(t,n.bullets,c,i,a):n.body&&t.addText(n.body,{x:c.x,y:c.y,w:c.w,h:c.h,fontSize:i.fonts.sizes.body,fontFace:i.fonts.body,color:i.colors.text.replace("#",""),valign:"top"}),s&&l){const u=o.includes("left")?Gt.imageLeft:Gt.imageRight;Jue(t,s,u)}}function f0n(e,t,r,n,o,i){if(n==="image-full-overlay"&&i){const s=FC(i);s?(e.background={data:s},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:50}}),e.addText(t,{x:.5,y:4.2,w:9,h:1,fontSize:o.fonts.sizes.heading,fontFace:o.fonts.heading,color:"FFFFFF",bold:!0,fit:Ot})):Os(e,t,o)}else n==="image-centered"||n==="image-full-overlay"?(Os(e,t,o),i?Jue(e,i,Gt.imageCentered):(e.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"}}),e.addText("\u{1F4F7}",{x:1.5,y:2.8,w:7,h:1,fontSize:48,align:"center",valign:"middle",fit:Ot}),e.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:Ot})),r.caption&&e.addText(r.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:Ot})):Xue({slide:e,title:t,content:r,layout:n,theme:o,imageBuffer:i})}function Ccr(e,t,r,n,o){Os(e,t,n,!1);const i={headerY:o?.headerY??1.3,headerHeight:o?.headerHeight??.5,bulletsStartY:o?.bulletsStartY??2,columnGap:o?.columnGap??.3,highlightFirstColumn:o?.highlightFirstColumn??!0},s=r.length;if(s===0)return;const a=9,l=(s-1)*i.columnGap,c=(a-l)/s,u=.5;r.forEach((d,p)=>{if(!d)return;const m=u+p*(c+i.columnGap),f=i.highlightFirstColumn&&p===0;if(d.title){e.addShape("roundRect",{x:m,y:i.headerY,w:c,h:i.headerHeight,fill:{color:f?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05});const g=s<=2?n.fonts.sizes.body:n.fonts.sizes.body-2;e.addText(d.title,{x:m,y:i.headerY,w:c,h:i.headerHeight,fontSize:g,fontFace:n.fonts.heading,color:f?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:Ot})}d.bullets&&d.bullets.length>0&&xcr({slide:e,bullets:d.bullets,startX:m,startY:i.bulletsStartY,width:c,theme:n})})}function g0n(e,t,r,n,o,i){const s=[];r.leftColumn&&s.push(r.leftColumn),r.rightColumn&&s.push(r.rightColumn),s.length>0&&Ccr(e,t,s,o,{highlightFirstColumn:!0}),i&&!r.rightColumn?.bullets&&Jue(e,i,Gt.columnRight)}function y0n(e,t,r,n){const o=[];r.leftColumn&&o.push(r.leftColumn),r.centerColumn&&o.push(r.centerColumn),r.rightColumn&&o.push(r.rightColumn),o.length>0&&Ccr(e,t,o,n,{highlightFirstColumn:!0})}function v0n(e,t,r,n){if(e.addText("\u201C",{x:.5,y:1,w:1,h:1,fontSize:120,fontFace:"Georgia",color:n.colors.primary.replace("#",""),fit:Ot}),r.quote&&e.addText(r.quote,{x:Gt.quote.x,y:Gt.quote.y,w:Gt.quote.w,h:Gt.quote.h,fontSize:n.fonts.sizes.heading,fontFace:"Georgia",color:n.colors.text.replace("#",""),italic:!0,valign:"middle",fit:Ot}),r.quoteAuthor){let o=`\u2014 ${r.quoteAuthor}`;r.quoteAuthorTitle&&(o+=`, ${r.quoteAuthorTitle}`),e.addText(o,{x:Gt.quoteAuthor.x,y:Gt.quoteAuthor.y,w:Gt.quoteAuthor.w,h:Gt.quoteAuthor.h,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"right",fit:Ot})}}function w0n(e,t,r,n){if(Os(e,t,n),!r.statistics||r.statistics.length===0)return;const o=r.statistics.slice(0,4),i=9/o.length;o.forEach((s,a)=>{const l=.5+a*i;if(e.addText(s.value,{x:l,y:Gt.statRow.y,w:i-.2,h:1.2,fontSize:48,fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",fit:Ot}),e.addText(s.label,{x:l,y:Gt.statRow.y+1.3,w:i-.2,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),align:"center",fit:Ot}),s.change||s.trend){const c=s.trend==="up"?"22C55E":s.trend==="down"?"EF4444":n.colors.muted.replace("#",""),u=s.trend==="up"?"(+)":s.trend==="down"?"(-)":"";e.addText(`${u} ${s.change||""}`,{x:l,y:Gt.statRow.y+1.8,w:i-.2,h:.4,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:c,align:"center",fit:Ot})}})}function b0n(e,t,r,n,o){if(Os(e,t,o),!r.chartData||!r.chartData.series||r.chartData.series.length===0){e.addText("No chart data available",{x:Gt.chart.x,y:Gt.chart.y+1,w:Gt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:Ot});return}const i=r.chartData.series.filter(l=>l.name&&Array.isArray(l.labels)&&l.labels.length>0&&Array.isArray(l.values)&&l.values.length>0);if(i.length===0){e.addText("Invalid chart data format",{x:Gt.chart.x,y:Gt.chart.y+1,w:Gt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:Ot});return}const s=d0n(n),a=i.map(l=>({name:l.name,labels:l.labels,values:l.values}));e.addChart(s,a,{x:Gt.chart.x,y:Gt.chart.y,w:Gt.chart.w,h:Gt.chart.h,showTitle:!!r.chartData.title,title:r.chartData.title,showLegend:r.chartData.legendPosition!=="none",legendPos:Pcr[r.chartData.legendPosition||"bottom"]||"b",showValue:r.chartData.showLabels,chartColors:[o.colors.primary.replace("#",""),o.colors.secondary.replace("#",""),o.colors.accent.replace("#","")]})}function T0n(e,t,r,n){if(Os(e,t,n),!r.tableData)return;const{headers:o,rows:i,hasHeader:s}=r.tableData,a=[];s&&o&&a.push(o.map(l=>({text:l,options:{bold:!0,fill:{color:n.colors.primary.replace("#","")},color:n.colors.textOnPrimary.replace("#",""),align:"center"}}))),i.forEach((l,c)=>{a.push(l.map(u=>({text:u.text,options:{fill:{color:c%2===0?"F8FAFC":"FFFFFF"},color:n.colors.text.replace("#",""),align:u.align||"left"}})))}),e.addTable(a,{x:Gt.chart.x,y:Gt.chart.y,w:Gt.chart.w,colW:Array(o?.length||i[0]?.length||1).fill(Gt.chart.w/(o?.length||i[0]?.length||1)),fontSize:n.fonts.sizes.body-2,fontFace:n.fonts.body,border:{pt:.5,color:"E2E8F0"},autoPage:!0}),r.tableData.caption&&e.addText(r.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 _0n(e,t,r,n){if(Os(e,t,n),!r.timeline?.items)return;const o=r.timeline.items.slice(0,5);r.timeline.orientation!=="vertical"?E0n(e,o,n):S0n(e,o,n)}function E0n(e,t,r){const n=8/t.length,o=2.8;e.addShape("rect",{x:1,y:o,w:8,h:.02,fill:{color:r.colors.primary.replace("#","")}}),t.forEach((i,s)=>{const a=1+s*n+n/2-.15;e.addShape("ellipse",{x:a,y:o-.15,w:.3,h:.3,fill:{color:r.colors.primary.replace("#","")}}),e.addText(i.date,{x:a-n/2+.15,y:o-.8,w:n,h:.4,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.primary.replace("#",""),align:"center",bold:!0,fit:Ot}),e.addText(i.title,{x:a-n/2+.15,y:o+.4,w:n,h:.4,fontSize:r.fonts.sizes.body,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),align:"center",bold:!0,fit:Ot}),i.description&&e.addText(i.description,{x:a-n/2+.15,y:o+.85,w:n,h:.8,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.muted.replace("#",""),align:"center",fit:Ot})})}function S0n(e,t,r){const n=3/t.length,o=1.5;e.addShape("rect",{x:o,y:1.5,w:.04,h:3.5,fill:{color:r.colors.primary.replace("#","")}}),t.forEach((i,s)=>{const a=1.7+s*n;e.addShape("ellipse",{x:o-.12,y:a,w:.28,h:.28,fill:{color:r.colors.primary.replace("#","")}}),e.addText(i.date,{x:.3,y:a-.1,w:1,h:.3,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.primary.replace("#",""),bold:!0,fit:Ot}),e.addText(i.title,{x:2,y:a-.1,w:7,h:.4,fontSize:r.fonts.sizes.body,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),bold:!0,fit:Ot}),i.description&&e.addText(i.description,{x:2,y:a+.3,w:7,h:.4,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.muted.replace("#",""),fit:Ot})})}function k0n(e,t,r,n){if(Os(e,t,n),!r.processSteps)return;const o=r.processSteps.slice(0,5),i=8/o.length;o.forEach((s,a)=>{const l=1+a*i,c=i-.4;e.addShape("roundRect",{x:l,y:2,w:c,h:2,fill:{color:n.colors.primary.replace("#","")},rectRadius:.1}),e.addText(String(s.step),{x:l,y:2.1,w:c,h:.5,fontSize:24,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:Ot}),e.addText(s.title,{x:l,y:2.6,w:c,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:Ot}),s.description&&e.addText(s.description,{x:l,y:3.2,w:c,h:.7,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.textOnPrimary.replace("#",""),align:"center",fit:Ot}),a<o.length-1&&e.addShape("rightArrow",{x:l+c+.02,y:2.85,w:.35,h:.3,fill:{color:n.colors.primary.replace("#","")}})})}function x0n(e,t,r,n){if(Os(e,t,n,!1),!r.comparison?.columns)return;const o=r.comparison.columns.slice(0,2),i=4.2,s=2,l=5-s,c=Math.max(...o.map(p=>Math.min(p.items?.length||0,6))),u=c>0?Math.min(.7,(l-ST*c)/c):.5,d=u+ST;o.forEach((p,m)=>{const f=.5+m*4.8;e.addShape("roundRect",{x:f,y:1.4,w:i,h:.5,fill:{color:p.highlight?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05}),e.addText(p.title,{x:f,y:1.4,w:i,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:p.highlight?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:Ot});const g=(p.items||[]).slice(0,6),y=g.length>4?Math.max(12,n.fonts.sizes.body-2):n.fonts.sizes.body;g.forEach((v,w)=>{if(bT(v)){const b=wT(v),E=[{text:"\u2022 ",options:{fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#","")}},...TT(b,{fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#","")})];e.addText(E,{x:f+.2,y:s+w*d,w:i-.4,h:u,valign:"top",fit:Ot})}else e.addText(`\u2022 ${v}`,{x:f+.2,y:s+w*d,w:i-.4,h:u,fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top",fit:Ot})})})}function A0n(e,t,r,n){Os(e,t,n);const o=r.features||[],i=r.icons||[],s=o.length>0?o:i.map(c=>({title:c.label,description:c.description||"",icon:c.icon}));if(s.length===0)return;const a=Math.min(s.length,3),l=9/a;s.slice(0,6).forEach((c,u)=>{const d=Math.floor(u/a),m=.5+u%a*l,f=1.6+d*1.8;if(c.icon){const g=parseInt(c.icon,16);if(!Number.isNaN(g)&&g>=0&&g<=1114111){const y=String.fromCodePoint(g);e.addText(y,{x:m,y:f,w:l-.2,h:.6,fontSize:36,fontFace:"Segoe UI Emoji",color:n.colors.primary.replace("#",""),align:"center",fit:Ot})}}e.addText(c.title,{x:m,y:f+.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:Ot}),c.description&&e.addText(c.description,{x:m,y:f+1,w:l-.2,h:.6,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:Ot})})}function C0n(e,t,r,n){if(Os(e,t,n),!r.teamMembers)return;const o=r.teamMembers.slice(0,4),i=9/o.length;o.forEach((s,a)=>{const l=.5+a*i;e.addShape("ellipse",{x:l+(i-1.5)/2,y:1.6,w:1.5,h:1.5,fill:{color:n.colors.muted.replace("#","")}});const c=s.name.split(" ").map(u=>u[0]).join("").substring(0,2);e.addText(c,{x:l+(i-1.5)/2,y:2,w:1.5,h:.7,fontSize:28,fontFace:n.fonts.heading,color:"FFFFFF",align:"center",bold:!0,fit:Ot}),e.addText(s.name,{x:l,y:3.3,w:i-.2,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),align:"center",bold:!0,fit:Ot}),e.addText(s.role,{x:l,y:3.7,w:i-.2,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:Ot})})}function I0n(e,t,r,n){if(Os(e,t,n),r.bullets){const o=r.bullets.map(i=>({...i,icon:i.icon||"2713"}));Acr(e,o,Gt.contentFull,n,"conclusion")}r.cta&&e.addText(r.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:Ot})}function ET(e,t,r,n,o=!1){e.addShape("roundRect",{x:t.x,y:t.y,w:t.w,h:t.h,fill:{color:o?n.colors.primary.replace("#","")+"15":"F8F9FA"},line:{color:o?n.colors.primary.replace("#",""):"E5E7EB",width:1},rectRadius:.1});let i=t.y+.15,s=t.h-.3;return r&&(e.addText(r,{x:t.x+.15,y:t.y+.1,w:t.w-.3,h:.35,fontSize:14,fontFace:n.fonts.heading,color:o?n.colors.primary.replace("#",""):n.colors.text.replace("#",""),bold:!0,fit:Ot}),i=t.y+.45,s=t.h-.55),{contentY:i,contentH:s}}function Icr(e,t,r,n,o,i){if(!t||t.length===0)return;const s=Math.max(11,Math.min(14,16-t.length)),a=n.colors.text.replace("#","");t.forEach((l,c)=>{if(!l||!l.text)return;const u=o+c*(i/t.length);if(bT(l.text)){const d=wT(l.text),p=[{text:"\u2022 ",options:{fontSize:s,fontFace:n.fonts.body,color:a}},...TT(d,{fontSize:s,fontFace:n.fonts.body,color:a})];e.addText(p,{x:r.x+.15,y:u,w:r.w-.3,h:i/t.length,valign:"top",fit:Ot})}else e.addText(`\u2022 ${l.text}`,{x:r.x+.15,y:u,w:r.w-.3,h:i/t.length,fontSize:s,fontFace:n.fonts.body,color:a,valign:"top",fit:Ot})})}function Yue(e,t,r,n,o,i){e.addText(t.value,{x:r.x,y:o,w:r.w,h:i*.6,fontSize:Math.min(32,r.w*8),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",valign:"bottom",fit:Ot}),e.addText(t.label,{x:r.x,y:o+i*.6,w:r.w,h:i*.4,fontSize:11,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",valign:"top",fit:Ot})}function Rcr(e){const{slide:t,icon:r,label:n,description:o,pos:i,theme:s,contentY:a,contentH:l}=e,c=Math.min(.6,i.w*.2);t.addShape("ellipse",{x:i.x+(i.w-c)/2,y:a,w:c,h:c,fill:{color:s.colors.primary.replace("#","")}});const u=parseInt(r,16);if(Number.isNaN(u)||u<0||u>1114111){h.warn("[renderIconBoxInZone] Invalid icon code",{icon:r});return}const d=String.fromCodePoint(u);t.addText(d,{x:i.x+(i.w-c)/2,y:a,w:c,h:c,fontSize:16,color:"FFFFFF",align:"center",valign:"middle",fit:Ot}),t.addText(n,{x:i.x,y:a+c+.1,w:i.w,h:.3,fontSize:12,fontFace:s.fonts.heading,color:s.colors.text.replace("#",""),bold:!0,align:"center",fit:Ot}),o&&t.addText(o,{x:i.x+.1,y:a+c+.4,w:i.w-.2,h:l-c-.5,fontSize:10,fontFace:s.fonts.body,color:s.colors.muted.replace("#",""),align:"center",fit:Ot})}function Mcr(e,t,r,n,o,i){const s=t.type==="pie"?"pie":t.type==="line"?"line":"bar",a=t.series||[];if(a.length===0)return;const l=a.map(c=>({name:c.name||"Data",labels:c.labels||[],values:c.values||[]}));try{e.addChart(s,l,{x:r.x+.1,y:o,w:r.w-.2,h:i,showLegend:!1,showTitle:!1,chartColors:[n.colors.primary.replace("#",""),n.colors.secondary.replace("#",""),n.colors.accent.replace("#",""),n.colors.muted.replace("#","")]})}catch{e.addText("Chart",{x:r.x,y:o,w:r.w,h:i,fontSize:14,color:n.colors.muted.replace("#",""),align:"center",valign:"middle",fit:Ot})}}function R0n(e,t,r,n){Os(e,t,n,!1);const o=Zs[r.layout]||Zs["left-right"];(r.zones||[]).forEach((s,a)=>{if(a>=o.length)return;const l=o[a],{contentY:c,contentH:u}=ET(e,l,s.title,n,s.isPrimary);switch(s.type){case"bullets":Array.isArray(s.data)&&Icr(e,s.data,l,n,c,u);break;case"stats":s.data&&typeof s.data=="object"&&Yue(e,s.data,l,n,c,u);break;case"icon-box":if(s.data&&typeof s.data=="object"){const d=s.data;Rcr({slide:e,icon:d.icon,label:d.label,description:d.description,pos:l,theme:n,contentY:c,contentH:u})}break;case"chart":s.data&&typeof s.data=="object"&&Mcr(e,s.data,l,n,c,u);break;case"text-box":typeof s.data=="string"&&e.addText(s.data,{x:l.x+.15,y:c,w:l.w-.3,h:u,fontSize:12,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top"});break}})}function M0n(e,t,r,n){if(Os(e,t,n,!1),r.bullets&&r.bullets.length>0){const o=Zs["left-right"][0],{contentY:i,contentH:s}=ET(e,o,r.leftColumn?.title,n,!0);Icr(e,r.bullets,o,n,i,s)}if(r.chartData){const o=Zs["left-right"][1],{contentY:i,contentH:s}=ET(e,o,"Data",n,!1);Mcr(e,r.chartData,o,n,i,s)}else if(r.statistics&&r.statistics.length>0){const o=Zs["left-right"][1];ET(e,o,"Metrics",n,!1);const i=r.statistics.slice(0,3),s=o.h/i.length;i.forEach((a,l)=>{Yue(e,a,{...o,y:o.y+l*s,h:s},n,o.y+l*s+.1,s-.2)})}}function P0n(e,t,r,n){Os(e,t,n,!1);const o=r.statistics||[];if(o.length===0)return;let i;o.length<=2?i=Zs["left-right"]:o.length<=3?i=Zs["three-cols"]:o.length<=4?i=Zs.quadrants:o.length<=5?i=Zs["five-boxes"]:i=Zs["six-boxes"],o.slice(0,i.length).forEach((s,a)=>{const l=i[a],c=a===0,{contentY:u,contentH:d}=ET(e,l,void 0,n,c);Yue(e,s,l,n,u,d)})}function O0n(e,t,r,n){Os(e,t,n,!1);const o=r.icons||r.features||[];if(o.length===0)return;let i;o.length<=2?i=Zs["left-right"]:o.length<=3?i=Zs["three-cols"]:o.length<=4?i=Zs.quadrants:o.length<=5?i=Zs["five-boxes"]:i=Zs["six-boxes"],o.slice(0,i.length).forEach((s,a)=>{const l=i[a],c=a===0,{contentY:u,contentH:d}=ET(e,l,void 0,n,c),p=s.icon||"1F4A1",m=s.title||s.label||"",f=s.description;Rcr({slide:e,icon:p,label:m,description:f,pos:l,theme:n,contentY:u,contentH:d})})}var ST,Ot,Gt,Pcr,Zs,D0n=S({"src/lib/features/ppt/slideRenderers.ts"(){"use strict";z(),vT(),Kue(),ST=.1,Ot="shrink",Gt={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}},Pcr={top:"t",bottom:"b",left:"l",right:"r"},Zs={"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}]}}});async function N0n(){if($C)return $C;const t=(await Al("pptxgenjs","PPT generation")).default;return $C=typeof t=="function"?t:t.default,$C}var $C,Ocr,Dcr=S({async"src/lib/features/ppt/slideGenerator.ts"(){"use strict";Mx(),hn(),lt(),vT(),z(),gd(),et(),Zn(),D0n(),$C=null,Ocr=class{theme;config;neurolink;imageLimit;userImageIndex=0;constructor(e){this.config=e,this.theme=typeof e.theme=="string"?qlr(e.theme):e.theme,this.neurolink=e.neurolink||null,this.imageLimit=qg(jue)}getNextUserImage(){const e=this.config.userImages;if(!e||e.length===0)return;const 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://")){const n=await Be(fetch(e),15e3,ve.toolTimeout("userImageFetch",15e3));if(!n.ok){h.warn(`[SlideGenerator] Failed to fetch user image: ${e}`);return}return Buffer.from(await n.arrayBuffer())}return await(await Promise.resolve().then(()=>(yi(),zg))).readFile(e)}catch(r){h.warn("[SlideGenerator] Failed to load user image",{error:r instanceof Error?r.message:String(r)});return}}async generateSlide(e){const t=Ce.createSpan("ppt.generation","ppt.generateSlide",{"ppt.operation":"generateSlide","ppt.slideIndex":e.slideNumber,"ppt.theme":this.theme.name}),r=Date.now();try{let n,o;if(x$(e.type)){const a=this.getNextUserImage();if(a&&(h.info(`[SlideGenerator] \u{1F4F7} Using user-provided image for slide ${e.slideNumber}: "${e.title}"`),n=await this.loadUserImage(a),n&&(o={prompt:"User-provided image",model:"user-upload",generatedAt:new Date})),!n&&this.config.generateAIImages&&e.imagePrompt){h.info(`[SlideGenerator] \u23F3 Generating AI image for slide ${e.slideNumber}: "${e.title}"...`);const l=await this.generateImage(e.imagePrompt,e.type);l&&(n=l.buffer,o={prompt:e.imagePrompt,model:l.model,generatedAt:new Date})}}const i=Date.now()-r;h.debug(`[SlideGenerator] Generated slide ${e.slideNumber} (${e.type})`,{hasImage:!!n,generationTime:i});const s=Ce.endSpan(t,1);return rt().recordSpan(s),{slideNumber:e.slideNumber,schema:e,imageBuffer:n,imageMetadata:o,generationTime:i}}catch(n){const o=Ce.endSpan(t,2);o.statusMessage=n instanceof Error?n.message:String(n),rt().recordSpan(o);const i=n instanceof Me?n:ve.toolExecutionFailed("slideGenerator",n instanceof Error?n:new Error(String(n)));return h.error(`[SlideGenerator] Failed to generate slide ${e.slideNumber}`,{error:i.message,type:e.type}),{slideNumber:e.slideNumber,schema:e,generationTime:Date.now()-r}}}async generateSlides(e){const t=Date.now(),r=this.config.generateAIImages?e.filter(c=>c.imagePrompt&&x$(c.type)).length:0,n=this.config.userImages?.length??0;h.info(`[SlideGenerator] Generating ${e.length} slides...`,{theme:this.theme.name,generateAIImages:this.config.generateAIImages,slidesNeedingAIImages:r,userImagesProvided:n}),this.userImageIndex=0;const o=e.map(c=>this.imageLimit(()=>this.generateSlide(c))),i=await Promise.all(o),s=i.filter(c=>c.imageBuffer).length,a=this.config.generateAIImages?e.filter(c=>c.imagePrompt&&x$(c.type)&&!i.find(u=>u.slideNumber===c.slideNumber)?.imageBuffer).length:0,l=Date.now()-t;return h.info("[SlideGenerator] Slide generation complete",{totalSlides:i.length,totalImages:s,failedImages:a,generationTime:l}),{slides:i,totalImages:s,failedImages:a,generationTime:l}}renderSlide(e,t,r,n){const{schema:o,imageBuffer:i}=t,s=e.addSlide();return this.applyBackground(s,o.type),this.applyLayout(s,o,i),o.type!=="title"&&o.type!=="thank-you"&&this.addSlideNumber(s,r,n),this.addLogo(s,o.type),o.speakerNotes&&s.addNotes(o.speakerNotes),s}async generateImage(e,t){if(!this.neurolink)return h.warn("[SlideGenerator] No NeuroLink instance provided, skipping image generation"),null;try{const r=Hlr(e,this.theme.name);h.debug(`[SlideGenerator] Generating image for ${t}`,{promptPreview:r.substring(0,100)});const n=await Be(this.neurolink.generate({input:{text:r},provider:this.config.provider||"vertex",model:this.config.imageModel||"gemini-2.5-flash-image"}),P$,ve.toolTimeout("imageGeneration",P$));if(!n||!n.imageOutput?.base64)return h.warn(`[SlideGenerator] No image data returned for ${t}`),null;const o=Buffer.from(n.imageOutput.base64,"base64");return o.length<100?(h.warn(`[SlideGenerator] Image buffer too small (${o.length} bytes) for ${t}`),null):(o[0]===255&&o[1]===216&&o[2]===255||o[0]===137&&o[1]===80&&o[2]===78&&o[3]===71||o[0]===71&&o[1]===73&&o[2]===70||o[0]===82&&o[1]===73&&o[2]===70&&o[3]===70||h.warn(`[SlideGenerator] Unknown image format for ${t}, magic bytes: ${o.slice(0,4).toString("hex")}`),h.debug(`[SlideGenerator] Image generated successfully for ${t}`,{size:o.length,format:o[0]===255?"JPEG":o[0]===137?"PNG":o[0]===71?"GIF":"unknown"}),{buffer:o,model:n.model||this.config.imageModel})}catch(r){const n=r instanceof Me?r:ve.toolExecutionFailed("imageGeneration",r instanceof Error?r:new Error(String(r)));return h.error("[SlideGenerator] Image generation failed",{error:n.message,slideType:t}),null}}applyBackground(e,t){e.background={color:this.theme.colors.background.replace("#","")}}applyLayout(e,t,r){const{type:n,layout:o,title:i,content:s}=t;switch(n){case"title":p0n(e,i,s,this.theme,r);break;case"section-header":m0n(e,i,s,this.theme);break;case"content":case"bullets":case"agenda":case"numbered-list":Xue({slide:e,title:i,content:s,layout:o,theme:this.theme,imageBuffer:r,slideType:n});break;case"image-focus":case"image-left":case"image-right":case"full-bleed-image":f0n(e,i,s,o,this.theme,r);break;case"two-column":case"split-content":g0n(e,i,s,o,this.theme,r);break;case"three-column":y0n(e,i,s,this.theme);break;case"quote":v0n(e,i,s,this.theme);break;case"statistics":w0n(e,i,s,this.theme);break;case"chart-bar":case"chart-line":case"chart-pie":case"chart-area":b0n(e,i,s,n,this.theme);break;case"table":T0n(e,i,s,this.theme);break;case"timeline":_0n(e,i,s,this.theme);break;case"process-flow":k0n(e,i,s,this.theme);break;case"comparison":x0n(e,i,s,this.theme);break;case"features":case"icons":A0n(e,i,s,this.theme);break;case"team":C0n(e,i,s,this.theme);break;case"conclusion":I0n(e,i,s,this.theme);break;case"thank-you":case"closing":h0n(e,i,s,this.theme,r);break;case"dashboard":s.dashboard&&R0n(e,i,s.dashboard,this.theme);break;case"mixed-content":M0n(e,i,s,this.theme);break;case"stats-grid":P0n(e,i,s,this.theme);break;case"icon-grid":O0n(e,i,s,this.theme);break;case"blank":break;default:Xue({slide:e,title:i,content:s,layout:o,theme:this.theme,imageBuffer:r,slideType:n})}}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(ws(e)){const t=sp(e),r=e.split(".").pop()?.toLowerCase();return`data:${r==="svg"?"image/svg+xml":r==="jpg"||r==="jpeg"?"image/jpeg":"image/png"};base64,${t.toString("base64")}`}}catch{h.warn("[SlideGenerator] Could not read logo file, treating as base64")}return`data:image/png;base64,${e}`}addLogo(e,t){const r=this.getLogoConfig();if(!r)return;const n=r.showOn||"all-slides";if(n==="title-only"&&t!=="title"||n==="title-and-closing"&&t!=="title"&&t!=="thank-you"&&t!=="closing")return;const o=this.getLogoDataUri(r.data),i=r.position||"bottom-right",s=r.width||1,a=r.height||.4;let l,c;const u=Gt.logo;if(i==="title-only"?(l=u["bottom-right"].x,c=u["bottom-right"].y):(l=u[i].x,c=u[i].y),i==="top-right"||i==="bottom-right"){const{width:d}=_P[this.config.aspectRatio];l=d-s-.3}if(i==="bottom-left"||i==="bottom-right"){const{height:d}=_P[this.config.aspectRatio];c=d-a-.2}e.addImage({data:o,x:l,y:c,w:s,h:a,sizing:{type:"contain",w:s,h:a}})}addSlideNumber(e,t,r){e.addText(`${t} / ${r}`,{x:Gt.footer.x,y:Gt.footer.y,w:Gt.footer.w,h:Gt.footer.h,fontSize:this.theme.fonts.sizes.caption,fontFace:this.theme.fonts.body,color:this.theme.colors.muted.replace("#",""),align:"right"})}}}});function L0n(e){const t=e.trim();for(const{patterns:r,slideType:n,bulletStyle:o}of Lcr)for(const i of r)if(i.test(t))return{slideType:n,bulletStyle:o};return{slideType:null,bulletStyle:null}}function F0n(e){if(!e||e.length===0)return null;for(const t of e)for(const{pattern:r,bulletStyle:n}of Fcr)if(r.test(t.text))return n;return null}function Ncr(e){switch(e){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 $0n(e,t,r){const{slideType:n,bulletStyle:o}=L0n(e);if(n)return{type:n,bulletStyle:o||Ncr(n),wasInferred:!0};const i=r.bullets?F0n(r.bullets):null;return i?{type:t,bulletStyle:i,wasInferred:!0}:{type:t,bulletStyle:Ncr(t),wasInferred:!1}}function U0n(e,t){return(e.bullets?.length??0)>0||(e.leftColumn?.bullets?.length??0)>0||(e.rightColumn?.bullets?.length??0)>0||(e.centerColumn?.bullets?.length??0)>0?{...e,bullets:e.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t})),leftColumn:e.leftColumn?{...e.leftColumn,bullets:e.leftColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0,rightColumn:e.rightColumn?{...e.rightColumn,bullets:e.rightColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0,centerColumn:e.centerColumn?{...e.centerColumn,bullets:e.centerColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0}:e}var Lcr,Fcr,B0n=S({"src/lib/features/ppt/slideTypeInference.ts"(){"use strict";Lcr=[{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"}],Fcr=[{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 z0n(e,t="content"){return typeof e=="string"&&$cr.has(e)?e:(h.warn(`[ContentPlanner] Invalid slide type "${e}", using "${t}"`),t)}function G0n(e,t){if(typeof e=="string"&&Ucr.has(e))return e;const n=A$[t]?.[0]||"title-content";return h.warn(`[ContentPlanner] Invalid layout "${e}" for type "${t}", using "${n}"`),n}function q0n(e){if(e&&typeof e=="object"&&"text"in e){const t=e,r={text:String(t.text||"")};return Array.isArray(t.subBullets)&&(r.subBullets=t.subBullets.map(n=>String(n))),typeof t.icon=="string"&&(r.icon=t.icon),typeof t.emphasis=="boolean"&&(r.emphasis=t.emphasis),typeof t.fontSize=="number"&&t.fontSize>=8&&t.fontSize<=48&&(r.fontSize=t.fontSize),typeof t.bulletStyle=="string"&&Bcr.has(t.bulletStyle)&&(r.bulletStyle=t.bulletStyle),typeof t.color=="string"&&t.color.match(/^#?[0-9A-Fa-f]{6}$/)&&(r.color=t.color.startsWith("#")?t.color:`#${t.color}`),typeof t.bold=="boolean"&&(r.bold=t.bold),r.text?r:null}return typeof e=="string"&&e.trim()?{text:e.trim()}:null}function O$(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const n=q0n(r);n&&t.push(n)}return t}function j0n(e){if(!e||typeof e!="object")return{};const t=e,r={};if(t.bullets&&(r.bullets=O$(t.bullets)),t.leftColumn&&typeof t.leftColumn=="object"){const o=t.leftColumn;r.leftColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?O$(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(t.rightColumn&&typeof t.rightColumn=="object"){const o=t.rightColumn;r.rightColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?O$(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(t.centerColumn&&typeof t.centerColumn=="object"){const o=t.centerColumn;r.centerColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?O$(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}const 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(const o of n)t[o]!==void 0&&(r[o]=t[o]);return r}function V0n(e,t){if(!e||typeof e!="object")throw new Ll("AI returned invalid response: expected object",gu.INVALID_AI_RESPONSE,{received:typeof e});const r=e;if(typeof r.title!="string"||!r.title.trim())throw new Ll("AI response missing valid 'title' field",gu.INVALID_AI_RESPONSE,{field:"title",received:r.title});if(!Array.isArray(r.slides))throw new Ll("AI response missing 'slides' array",gu.INVALID_AI_RESPONSE,{field:"slides",received:typeof r.slides});r.slides.length!==t&&h.warn(`[ContentPlanner] AI returned ${r.slides.length} slides, expected ${t}. Adjusting...`);const n=[];for(let o=0;o<r.slides.length;o++){const i=r.slides[o];if(!i||typeof i!="object")throw new Ll(`Invalid slide at index ${o}`,gu.INVALID_AI_RESPONSE,{index:o,received:typeof i});typeof i.title!="string"&&(i.title=`Slide ${o+1}`,h.warn(`[ContentPlanner] Slide ${o+1} missing title, using default`));const s=z0n(i.type,"content"),a=j0n(i.content),{type:l,bulletStyle:c,wasInferred:u}=$0n(i.title,s,a),d=u&&l!==s?l:s;u&&l!==s&&h.debug(`[ContentPlanner] Slide ${o+1} type inferred from title: "${i.title}" \u2192 ${d}`);const p=U0n(a,c),m=G0n(i.layout,d);typeof i.speakerNotes!="string"&&(i.speakerNotes=""),i.imagePrompt!==null&&typeof i.imagePrompt!="string"&&(i.imagePrompt=null),n.push({slideNumber:o+1,type:d,layout:m,title:i.title,content:p,imagePrompt:i.imagePrompt,speakerNotes:i.speakerNotes})}return{title:r.title,totalSlides:n.length,audience:r.audience||"general",tone:r.tone||"professional",theme:r.theme||"modern",slides:n,keyMessages:Array.isArray(r.keyMessages)?r.keyMessages:void 0}}function H0n(e){const t=e.trim(),r=[],n=t.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);n&&n[1]&&r.push(n[1].trim()),t.startsWith("```")&&r.push(t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""));const o=t.indexOf("{"),i=t.indexOf("["),s=o===-1?i:i===-1?o:Math.min(o,i);if(s>0){const c=t[s]==="{"?"}":"]",u=t.lastIndexOf(c);u>s&&r.push(t.slice(s,u+1))}r.push(t);const a=[];for(const l of r)try{return JSON.parse(l)}catch(c){a.push(c instanceof Error?c.message:String(c))}throw new Ll(`Failed to parse AI response as JSON: ${a[a.length-1]}`,gu.INVALID_AI_RESPONSE,{contentPreview:e.substring(0,500),parseError:a.join(" | ")})}async function W0n(e,t){const r=Date.now(),n=`session-${Date.now()}`;h.info("[ContentPlanner] Starting content planning",{topic:e.topic.substring(0,100),pages:e.pages,audience:e.audience,tone:e.tone,theme:e.theme,generateAIImages:e.generateAIImages,provider:e.provider,model:e.model,sessionId:n});const o=Vlr({topic:e.topic,pages:e.pages,audience:e.audience,tone:e.tone,theme:e.theme,generateAIImages:e.generateAIImages,modelInfo:{name:e.model||"unknown",provider:e.provider||"auto-selected"}});try{const i=await t.generate({prompt:o,systemPrompt:Gue,temperature:.7,maxTokens:8192,disableTools:!0,timeout:que});if(!i||!i.content)throw new Ll("AI provider returned empty response",gu.PLANNING_FAILED,{provider:e.provider});const s=Date.now()-r;h.debug("[ContentPlanner] AI response received",{contentLength:i.content.length,planningTime:s});const a=H0n(i.content),l=V0n(a,e.pages);return h.info("[ContentPlanner] Content plan generated successfully",{title:l.title,totalSlides:l.totalSlides,planningTime:s,keyMessages:l.keyMessages?.length||0}),l}catch(i){if(i instanceof Ll)throw i;const s=i instanceof Error?i.message:String(i);throw new Ll(`Content planning failed: ${s}`,gu.PLANNING_FAILED,{topic:e.topic.substring(0,100),provider:e.provider},i instanceof Error?i:void 0)}}function K0n(e){return e.slides.length>0&&e.slides[0].type!=="title"&&(e.slides[0]={...e.slides[0],type:"title",layout:"title-centered"}),e}function J0n(e){const t=e.slides.length-1;return t>=0&&e.slides[t].type!=="thank-you"&&(e.slides[t]={...e.slides[t],type:"thank-you",layout:"contact-info"}),e}function X0n(e){let t={...e,slides:[...e.slides]};return t=K0n(t),t=J0n(t),t}var $cr,Ucr,Bcr,Y0n=S({"src/lib/features/ppt/contentPlanner.ts"(){"use strict";Vue(),vT(),B0n(),z(),$cr=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"]),Ucr=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"]),Bcr=new Set(["disc","number","checkmark","arrow","dash","none"])}}),zcr={};ce(zcr,{generatePresentation:()=>Z0n});async function Z0n(e){const t=Ce.createSpan("ppt.generation","ppt.orchestrate",{"ppt.operation":"orchestrate","ppt.slideCount":e.context.pages,"ppt.theme":typeof e.context.theme=="string"?e.context.theme:"custom"}),r={startTime:Date.now(),contentPlan:null,slides:null,outputPath:null},{context:n,provider:o,providerName:i,modelName:s,neurolink:a,imageProvider:l,imageModel:c}=e;h.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{h.info("[PresentationOrchestrator] Step 1: Content planning...");const u=await Be(W0n(n,o),xc/2,ve.toolTimeout("contentPlanning",xc/2));r.contentPlan=X0n(u),t.attributes["ppt.slideCount"]=r.contentPlan.totalSlides,t.attributes["ppt.theme"]=typeof r.contentPlan.theme=="string"?r.contentPlan.theme:"custom",h.info("[PresentationOrchestrator] Content plan ready",{title:r.contentPlan.title,totalSlides:r.contentPlan.totalSlides,theme:r.contentPlan.theme,audience:r.contentPlan.audience,tone:r.contentPlan.tone}),h.info("[PresentationOrchestrator] Step 2: Generating slides...");const d=n.logo??null,p=_cr(d),f={theme:r.contentPlan.theme||n.theme,generateAIImages:n.generateAIImages,aspectRatio:n.aspectRatio,provider:l??n.provider??"vertex",imageModel:c??"gemini-2.5-flash-image",logo:p??void 0,userImages:n.images,neurolink:a},g=new Ocr(f),y=await Be(g.generateSlides(r.contentPlan.slides),xc/2,ve.toolTimeout("slideGeneration",xc/2));r.slides=y.slides,h.info("[PresentationOrchestrator] Slides generated",{totalSlides:r.slides.length,totalImages:y.totalImages,failedImages:y.failedImages,generationTime:y.generationTime}),h.info("[PresentationOrchestrator] Step 3: Assembling PPTX...");const v=await N0n(),w=new v;w.title=r.contentPlan.title,w.subject=`Generated presentation about: ${n.topic.substring(0,100)}`,w.author="NeuroLink PPT Generator",w.company="NeuroLink",w.layout=Ecr(n.aspectRatio);const b=[...r.slides].sort((P,O)=>P.slideNumber-O.slideNumber);for(let P=0;P<b.length;P++){const O=b[P];g.renderSlide(w,O,P+1,b.length)}h.info("[PresentationOrchestrator] PPTX assembled",{totalSlides:b.length,layout:w.layout,title:w.title}),h.info("[PresentationOrchestrator] Step 4: Writing file..."),r.outputPath=vcr(n),await Be(wcr(r.outputPath),xc/4,ve.toolTimeout("outputDirectory",xc/4)),await Be(w.writeFile({fileName:r.outputPath}),xc/4,ve.toolTimeout("pptxWrite",xc/4));let E=0;try{E=(await Be(ko(r.outputPath),xc/8,ve.toolTimeout("pptxStat",xc/8))).size}catch{h.warn("[PresentationOrchestrator] Could not get file size")}const k=Date.now()-r.startTime;h.info("[PresentationOrchestrator] Presentation generation complete",{filePath:r.outputPath,fileSize:E,totalSlides:b.length,totalTime:k});const x=Ce.endSpan(t,1);rt().recordSpan(x),a?.recordMetricsSpan(x);const A=r.contentPlan?.theme||n.theme,R=r.contentPlan?.audience||n.audience,C=r.contentPlan?.tone||n.tone;return{filePath:r.outputPath,totalSlides:b.length,format:"pptx",provider:i,model:s,metadata:{theme:A,audience:R,tone:C,imageModel:n.generateAIImages?c??"gemini-2.5-flash-image":"",fileSize:E>0?E:0}}}catch(u){const d=Ce.endSpan(t,2);if(d.statusMessage=u instanceof Error?u.message:String(u),rt().recordSpan(d),a?.recordMetricsSpan(d),u instanceof Ll)throw h.error("[PresentationOrchestrator] Generation failed",{error:u.message,code:u.code,context:u.context}),u;const p=Scr(u);throw h.error("[PresentationOrchestrator] Unexpected error",{error:p.message,stage:Hue(r)}),new Ll(`Presentation generation failed: ${p.message}`,gu.ASSEMBLY_FAILED,{topic:n.topic.substring(0,100),stage:Hue(r),elapsedTime:Date.now()-r.startTime},p)}}var Q0n=S({async"src/lib/features/ppt/presentationOrchestrator.ts"(){"use strict";await Dcr(),yi(),Vue(),Y0n(),await Dcr(),vT(),z(),et(),Zn(),Kue()}}),Gcr={};ce(Gcr,{MUSIC_ERROR_CODES:()=>Yt,MusicError:()=>Kt,MusicProcessor:()=>Gp});var Yt,Kt,Gp,qp=S({"src/lib/utils/musicProcessor.ts"(){"use strict";Zn(),et(),z(),bw(),Yt={PROVIDER_NOT_SUPPORTED:"MUSIC_PROVIDER_NOT_SUPPORTED",PROVIDER_NOT_CONFIGURED:"MUSIC_PROVIDER_NOT_CONFIGURED",GENERATION_FAILED:"MUSIC_GENERATION_FAILED",POLL_TIMEOUT:"MUSIC_POLL_TIMEOUT",PROMPT_REQUIRED:"MUSIC_PROMPT_REQUIRED",DURATION_INVALID:"MUSIC_DURATION_INVALID",INVALID_INPUT:"MUSIC_INVALID_INPUT"},Kt=class extends Me{constructor(e){super({code:e.code,message:e.message,category:e.category??"execution",severity:e.severity??"high",retriable:e.retriable??!1,context:e.context,originalError:e.originalError}),this.name="MusicError"}},Gp=class{static registry=new Fg("MusicProcessor");static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),h.debug(`[MusicProcessor] Registered music handler: ${r}`)}static supports(e){return this.registry.supports(e)}static listProviders(){return this.registry.list()}static getHandler(e){return this.registry.get(e)}static clearHandlers(){this.registry.clear()}static buildSpanAttributes(e,t){return{"music.operation":"generate","music.provider":e,"music.duration":t.duration,"music.format":t.format,"music.genre":t.genre,"music.mood":t.mood}}static async generate(e,t){const r=Ce.createSpan("media.generation","music.generate",this.buildSpanAttributes(e,t));try{const n=t.prompt?.trim();if(!n)throw new Kt({code:Yt.PROMPT_REQUIRED,message:"Music generation requires a non-empty prompt",category:"validation",severity:"low",retriable:!1,context:{provider:e}});const o=this.getHandler(e);if(!o)throw new Kt({code:Yt.PROVIDER_NOT_SUPPORTED,message:`Music provider "${e}" is not registered. Available: ${this.listProviders().join(", ")}`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!o.isConfigured())throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:`Music provider "${e}" is not configured. Set the required credentials.`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});if(t.duration!==void 0&&o.maxDurationSeconds!==void 0&&t.duration>o.maxDurationSeconds)throw new Kt({code:Yt.DURATION_INVALID,message:`Requested duration (${t.duration}s) exceeds provider maximum (${o.maxDurationSeconds}s) for "${e}"`,category:"validation",severity:"medium",retriable:!1,context:{provider:e,requested:t.duration,maximum:o.maxDurationSeconds}});h.debug(`[MusicProcessor] Starting music generation with provider: ${e}`);const i=await o.generate({...t,prompt:n}),s=Ce.endSpan(r,1);return rt().recordSpan(s),h.info(`[MusicProcessor] Generated ${i.size} bytes (${e})`),i}catch(n){const o=Ce.endSpan(r,2,n instanceof Error?n.message:String(n));if(rt().recordSpan(o),n instanceof Kt)throw n;const i=n instanceof Error?n.message:String(n);throw new Kt({code:Yt.GENERATION_FAILED,message:`Music generation failed for provider "${e}": ${i}`,category:"execution",severity:"high",retriable:!0,context:{provider:e,duration:t.duration,format:t.format,genre:t.genre,mood:t.mood,tempo:t.tempo},originalError:n instanceof Error?n:void 0})}}}}}),qcr,u0,jcr,Vcr,kT,Hcr=S({"src/lib/music/providers/BeatovenMusic.ts"(){"use strict";z(),qp(),Ta(),OC(),qcr="https://public-api.beatoven.ai",u0=3e4,jcr=3e3,Vcr=5*6e4,kT=class{maxDurationSeconds=300;supportedFormats=["mp3","wav"];supportedGenres=["ambient","cinematic","corporate","lo-fi","rock","pop","electronic","orchestral","folk"];apiKey;baseUrl;constructor(e){const t=(e??process.env.BEATOVEN_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.BEATOVEN_BASE_URL??qcr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:"BEATOVEN_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});const t=Date.now(),r=e.format??"mp3";this.supportedFormats.includes(r)||h.warn(`[BeatovenMusic] Format "${r}" not supported \u2014 falling back to "mp3"`);const n=this.supportedFormats.includes(r)?r:"mp3",i=(await this.submitCompose(e,n)).task_id,s=await this.pollUntilComposed(i,e.timeout??Vcr),a=s.meta?.track_url;if(!a)throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven task ${i} completed but no track_url returned`,category:"execution",severity:"high",retriable:!1,context:{taskId:i,taskResult:s}});const l=await this.downloadTrack(a),c=Date.now()-t;return h.info(`[BeatovenMusic] Generated ${l.length} bytes (${n}) in ${c}ms \u2014 task ${i}`),{buffer:l,format:n,size:l.length,duration:s.meta?.duration,provider:"beatoven",metadata:{latency:c,provider:"beatoven",model:"beatoven-default",jobId:i,trackId:s.meta?.track_id,projectId:s.meta?.project_id,requestedFormat:e.format}}}async submitCompose(e,t){const r=(e.duration??60)*1e3,n=[e.prompt];e.genre&&n.push(`Genre: ${e.genre}`),e.mood&&n.push(`Mood: ${e.mood}`),e.tempo!==void 0&&n.push(`Tempo: ${e.tempo} BPM`);const o={prompt:{text:n.join(". ")},duration:r,format:t},i=new AbortController,s=setTimeout(()=>i.abort(),u0);let a;try{a=await fetch(`${this.baseUrl}/api/v1/tracks/compose`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal})}catch(c){throw c instanceof Error&&c.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven compose request timed out after ${u0/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:c}):new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven compose network error: ${c instanceof Error?c.message:String(c)}`,category:"network",severity:"high",retriable:!0,originalError:c instanceof Error?c:void 0})}finally{clearTimeout(s)}if(!a.ok){const c=await a.text(),u=a.status===408||a.status===429||a.status>=500;throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven compose failed: ${a.status} \u2014 ${c}`,category:u?"network":"execution",severity:"high",retriable:u,context:{status:a.status,body:c}})}const l=await a.json();if(!l.task_id)throw new Kt({code:Yt.GENERATION_FAILED,message:"Beatoven compose response missing task_id",category:"execution",severity:"high",retriable:!1,context:{response:l}});return l}async pollUntilComposed(e,t){const r=Date.now();for(;Date.now()-r<t;){const n=await this.fetchTaskStatus(e);if(n.status==="composed")return n;if(n.status==="failed")throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven task ${e} failed: ${n.message??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{taskId:e,status:n}});await new Promise(o=>setTimeout(o,jcr))}throw new Kt({code:Yt.POLL_TIMEOUT,message:`Beatoven task ${e} did not complete within ${Math.round(t/1e3)}s`,category:"timeout",severity:"medium",retriable:!0,context:{taskId:e,totalTimeoutMs:t}})}async fetchTaskStatus(e){const t=new AbortController,r=setTimeout(()=>t.abort(),u0);let n;try{n=await fetch(`${this.baseUrl}/api/v1/tasks/${e}`,{method:"GET",headers:{Authorization:`Bearer ${this.apiKey}`},signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven status poll timed out after ${u0/1e3}s`,category:"network",severity:"medium",retriable:!0,originalError:o}):new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven status poll network error: ${o instanceof Error?o.message:String(o)}`,category:"network",severity:"medium",retriable:!0,originalError:o instanceof Error?o:void 0,context:{taskId:e}})}finally{clearTimeout(r)}if(!n.ok){const o=await n.text();throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven status request failed: ${n.status} \u2014 ${o}`,category:"execution",severity:"medium",retriable:n.status>=500,context:{status:n.status,taskId:e}})}return await n.json()}async downloadTrack(e){try{await PC(e)}catch(o){throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track URL rejected: ${o instanceof Error?o.message:String(o)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=new AbortController,r=setTimeout(()=>t.abort(),u0);let n;try{n=await fetch(e,{signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track download timed out after ${u0/1e3}s`,category:"network",severity:"medium",retriable:!0,originalError:o}):new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track download network error: ${o instanceof Error?o.message:String(o)}`,category:"network",severity:"medium",retriable:!0,originalError:o instanceof Error?o:void 0,context:{url:e}})}finally{clearTimeout(r)}if(!n.ok)throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track download failed: ${n.status}`,category:"network",severity:"medium",retriable:n.status>=500,context:{status:n.status,url:e}});try{return await l0(n,Vh,"Beatoven track")}catch(o){throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track download exceeded size limit: ${o instanceof Error?o.message:String(o)}`,category:"execution",severity:"high",retriable:!1,context:{url:e}})}}}}}),Wcr,Zue,xT,Kcr=S({"src/lib/music/providers/ElevenLabsMusic.ts"(){"use strict";qp(),z(),Ta(),Wcr="https://api.elevenlabs.io/v1",Zue=6e4,xT=class{maxDurationSeconds=22;supportedFormats=["mp3"];supportedGenres=["ambient","cinematic","lo-fi","electronic","orchestral","soundscape"];apiKey;baseUrl;constructor(e){const t=(e??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.ELEVENLABS_BASE_URL??Wcr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:"ELEVENLABS_API_KEY not configured (shared with ElevenLabs TTS \u2014 same account, different endpoint)",category:"configuration",severity:"high",retriable:!1});const t=e.prompt?.trim();if(!t)throw new Kt({code:Yt.INVALID_INPUT,message:"ElevenLabs Music requires a non-empty prompt",category:"validation",severity:"low",retriable:!1});const r=e.duration??8;if(r<=0||r>this.maxDurationSeconds)throw new Kt({code:Yt.INVALID_INPUT,message:`ElevenLabs Music duration must be between 1 and ${this.maxDurationSeconds} seconds; got ${r}`,category:"validation",severity:"low",retriable:!1,context:{requested:r,maximum:this.maxDurationSeconds}});const n=Date.now(),o=r,i={text:this.buildPrompt({...e,prompt:t}),duration_seconds:o,prompt_influence:.3},s=new AbortController,a=setTimeout(()=>s.abort(),Zue);let l;try{l=await fetch(`${this.baseUrl}/sound-generation`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json",Accept:"audio/mpeg"},body:JSON.stringify(i),signal:s.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`ElevenLabs Music request timed out after ${Zue/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:d}):new Kt({code:Yt.GENERATION_FAILED,message:`ElevenLabs Music network error: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"high",retriable:!0,originalError:d instanceof Error?d:void 0})}finally{clearTimeout(a)}if(!l.ok){const d=await l.text(),p=l.status===408||l.status===429||l.status>=500;throw new Kt({code:Yt.GENERATION_FAILED,message:`ElevenLabs Music synthesis failed: ${l.status} \u2014 ${d}`,category:p?"network":"execution",severity:"high",retriable:p,context:{status:l.status}})}const c=await l0(l,Vh,"ElevenLabs music"),u=Date.now()-n;return h.info(`[ElevenLabsMusic] Generated ${c.length} bytes in ${u}ms`),{buffer:c,format:"mp3",size:c.length,duration:o,provider:"elevenlabs-music",metadata:{latency:u,provider:"elevenlabs-music",model:"elevenlabs-sound-v1"}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}}}}),Jcr,Xcr,Que,AT,Ycr=S({"src/lib/music/providers/LyriaMusic.ts"(){"use strict";qp(),z(),Ft(),Jcr="https://generativelanguage.googleapis.com/v1beta",Xcr="lyria-3-pro-preview",Que=12e4,AT=class{maxDurationSeconds=30;supportedFormats=["wav"];supportedGenres=["ambient","classical","electronic","jazz","rock","pop","lo-fi","cinematic","orchestral","world"];apiKey;baseUrl;model;constructor(e){const t=(e??process.env.GOOGLE_AI_LYRIA_API_KEY??process.env.GOOGLE_API_KEY??process.env.GOOGLE_AI_API_KEY??process.env.GEMINI_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.LYRIA_BASE_URL??Jcr).replace(/\/$/,""),this.model=process.env.LYRIA_MODEL??Xcr}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:"Lyria requires one of: GOOGLE_API_KEY, GOOGLE_AI_LYRIA_API_KEY, GOOGLE_AI_API_KEY, or GEMINI_API_KEY",category:"configuration",severity:"high",retriable:!1});const t=Date.now(),r=Math.min(e.duration??16,this.maxDurationSeconds),o={contents:[{parts:[{text:`${this.buildPrompt(e)}. Duration: ${r} seconds`}]}],generationConfig:{responseModalities:["AUDIO"]}},i=new AbortController,s=setTimeout(()=>i.abort(),Que);let a;try{a=await fetch(`${this.baseUrl}/models/${this.model}:generateContent?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal})}catch(p){throw p instanceof Error&&p.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Lyria request timed out after ${Que/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:p}):p}finally{clearTimeout(s)}if(!a.ok){const p=await a.text(),m=a.status===408||a.status===429||a.status>=500;throw new Kt({code:Yt.GENERATION_FAILED,message:`Lyria generation failed: ${a.status} \u2014 ${gr(p)}`,category:m?"network":"execution",severity:"high",retriable:m,context:{status:a.status}})}const l=await a.json(),c=l.candidates?.[0]?.content?.parts?.find(p=>p.inlineData?.mimeType?.startsWith("audio/"));if(!c?.inlineData?.data)throw new Kt({code:Yt.GENERATION_FAILED,message:"Lyria response missing audio data",category:"execution",severity:"high",retriable:!1,context:{response:l}});const u=Buffer.from(c.inlineData.data,"base64"),d=Date.now()-t;return h.info(`[LyriaMusic] Generated ${u.length} bytes in ${d}ms \u2014 model ${this.model}`),{buffer:u,format:"wav",size:u.length,duration:r,provider:"lyria",metadata:{latency:d,provider:"lyria",model:this.model,sampleRate:48e3}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}}}});function Wh(e){const t=(e?.apiToken??process.env.REPLICATE_API_TOKEN??"").trim();return t?{apiToken:t,baseUrl:(e?.baseUrl??process.env.REPLICATE_BASE_URL??Zcr).replace(/\/$/,"")}:null}var Zcr,D$=S({"src/lib/adapters/replicate/auth.ts"(){"use strict";Zcr="https://api.replicate.com"}});async function evn(e,t,r){const n=e.baseUrl??"https://api.replicate.com",[o,i]=t.model.split(":",2),s=i?`${n}/v1/predictions`:`${n}/v1/models/${o}/predictions`,a=i?{version:i,input:t.input}:{input:t.input};return t.webhook&&(a.webhook=t.webhook),t.webhookEventsFilter&&t.webhookEventsFilter.length>0&&(a.webhook_events_filter=t.webhookEventsFilter),Fv(async()=>{const l=new AbortController,c=setTimeout(()=>l.abort(),CT);try{const u=await fetch(s,{method:"POST",headers:{Authorization:`Token ${e.apiToken}`,"Content-Type":"application/json",Prefer:"wait=60"},body:JSON.stringify(a),signal:l.signal});if(!u.ok){const d=await u.text();throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate predictions submit failed: ${u.status} \u2014 ${gr(d,500)}`,category:"network",severity:"high",retriable:u.status>=500||u.status===429,retryAfterMs:Lv(u.headers)})}return await u.json()}catch(u){throw u instanceof Me?u:u instanceof Error&&u.name==="AbortError"?new Me({code:je.OPERATION_ABORTED,message:`Replicate predictions submit timed out after ${CT/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:u}):u}finally{clearTimeout(c)}},void 0,"Replicate prediction submission",r)}async function tvn(e,t,r={}){const n=e.baseUrl??"https://api.replicate.com",o=Date.now(),i=r.timeoutMs??eur,s=r.pollIntervalMs??Qcr;for(;Date.now()-o<i;){if(r.abortSignal?.aborted)throw new Me({code:je.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1});const a=new AbortController,l=setTimeout(()=>a.abort(),CT),c=()=>a.abort();r.abortSignal?.addEventListener("abort",c,{once:!0});let u;try{u=await fetch(`${n}/v1/predictions/${t}`,{method:"GET",headers:{Authorization:`Token ${e.apiToken}`},signal:a.signal})}catch(p){throw p instanceof Me?p:p instanceof Error&&p.name==="AbortError"?r.abortSignal?.aborted?new Me({code:je.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1,originalError:p}):new Me({code:je.OPERATION_ABORTED,message:`Replicate poll request timed out after ${CT/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:p}):p}finally{r.abortSignal?.removeEventListener("abort",c),clearTimeout(l)}if(!u.ok){const p=await u.text();throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate poll failed: ${u.status} \u2014 ${gr(p,500)}`,category:"network",severity:"high",retriable:u.status>=500||u.status===429,retryAfterMs:Lv(u.headers)})}const d=await u.json();if(d.status==="succeeded")return d;if(d.status==="failed"||d.status==="canceled")throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${d.id} ${d.status}: ${d.error??"unknown"}`,category:"execution",severity:"high",retriable:d.status==="failed"});await new Promise((p,m)=>{const f=()=>{clearTimeout(g),m(new Me({code:je.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1}))},g=setTimeout(()=>{r.abortSignal?.removeEventListener("abort",f),p()},s);r.abortSignal?.addEventListener("abort",f,{once:!0})})}throw new Me({code:je.OPERATION_ABORTED,message:`Replicate prediction ${t} did not complete within ${Math.round(i/1e3)}s`,category:"timeout",severity:"high",retriable:!0})}async function UC(e,t,r={}){const n=await evn(e,t);if(n.status==="succeeded")return n;if(n.status==="failed"||n.status==="canceled")throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${n.id} ${n.status} on submit: ${n.error??"unknown"}`,category:"execution",severity:"high",retriable:n.status==="failed"});return tvn(e,n.id,r)}async function N$(e,t=c0){const r=e.output,n=Array.isArray(r)?r[0]:r;if(typeof n!="string")throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${e.id} output is not a URL: ${typeof r}`,category:"execution",severity:"high",retriable:!1});try{const o=await zp(n,{maxBytes:t,label:`Replicate prediction ${e.id}`,timeoutMs:CT});return h.debug(`[Replicate] Downloaded prediction ${e.id} output: ${o.length} bytes`),o}catch(o){if(o instanceof Me)throw o;const i=o instanceof Error?o.message:String(o);throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate output download failed: ${i} \u2014 ${n}`,category:"network",severity:"high",retriable:!0,originalError:o instanceof Error?o:void 0})}}var CT,Qcr,eur,L$=S({"src/lib/adapters/replicate/predictionLifecycle.ts"(){"use strict";z(),et(),Ft(),rp(),NP(),Md(),Ta(),CT=9e4,Qcr=2e3,eur=5*6e4}}),tur,IT,rur=S({"src/lib/music/providers/ReplicateMusic.ts"(){"use strict";qp(),z(),D$(),L$(),Ta(),OC(),tur="meta/musicgen:7be0f12c54a8d033a0fbd14418c9af98962da9a86f5ff7811f9b3423a1f0b7d7",IT=class{maxDurationSeconds=30;supportedFormats=["mp3","wav"];supportedGenres=["ambient","classical","electronic","rock","jazz","hip-hop","pop","lo-fi","cinematic","orchestral"];isConfigured(){return Wh()!==null}async generate(e){const t=Wh();if(!t)throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:"REPLICATE_API_TOKEN not configured",category:"configuration",severity:"high",retriable:!1});const r=Date.now(),n=e.model??tur,o=e.format??"mp3",i=this.supportedFormats.includes(o)?o:"mp3",s=Math.min(e.duration??8,this.maxDurationSeconds),a={prompt:this.buildPrompt(e),duration:s,output_format:i,model_version:"stereo-large",normalization_strategy:"loudness"};if(e.tempo!==void 0&&(a.bpm=e.tempo),e.referenceAudio){const d=await this.resolveBuffer(e.referenceAudio);a.input_audio=`data:audio/${this.detectAudioType(d)};base64,${d.toString("base64")}`}let l;try{l=await UC(t,{model:n,input:a})}catch(d){throw new Kt({code:Yt.GENERATION_FAILED,message:`Replicate music generation failed: ${d instanceof Error?d.message:String(d)}`,category:"execution",severity:"high",retriable:!0,context:{model:n,duration:s,format:i,hasReferenceAudio:e.referenceAudio!==void 0},originalError:d instanceof Error?d:void 0})}let c;try{c=await N$(l,Vh)}catch(d){throw new Kt({code:Yt.GENERATION_FAILED,message:`Replicate music download failed: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"medium",retriable:!0,context:{predictionId:l.id},originalError:d instanceof Error?d:void 0})}const u=Date.now()-r;return h.info(`[ReplicateMusic] Generated ${c.length} bytes in ${u}ms \u2014 model ${n}`),{buffer:c,format:i,size:c.length,duration:s,provider:"replicate",metadata:{latency:u,provider:"replicate",model:n,jobId:l.id}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}async resolveBuffer(e){if(Buffer.isBuffer(e))return e;if(!/^https:\/\//.test(e))throw new Kt({code:Yt.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await PC(e)}catch(i){throw new Kt({code:Yt.INVALID_INPUT,message:`Unsafe URL rejected: ${i instanceof Error?i.message:String(i)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=6e4,r=new AbortController,n=setTimeout(()=>r.abort(),t);let o;try{o=await fetch(e,{signal:r.signal})}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Replicate music reference-audio fetch timed out after ${t/1e3}s: ${e}`,category:"network",severity:"medium",retriable:!0}):i}finally{clearTimeout(n)}if(!o.ok)throw new Kt({code:Yt.GENERATION_FAILED,message:`Failed to fetch reference audio: ${e}: ${o.status}`,category:"network",severity:"medium",retriable:o.status>=500});try{return await l0(o,Vh,"Replicate reference audio")}catch(i){throw new Kt({code:Yt.INVALID_INPUT,message:`Replicate reference audio too large: ${i instanceof Error?i.message:String(i)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}}}}),ede={};ce(ede,{BeatovenMusic:()=>kT,BeatovenMusicHandler:()=>kT,ElevenLabsMusic:()=>xT,ElevenLabsMusicHandler:()=>xT,LyriaMusic:()=>AT,LyriaMusicHandler:()=>AT,MUSIC_ERROR_CODES:()=>Yt,MusicError:()=>Kt,MusicProcessor:()=>Gp,ReplicateMusic:()=>IT,ReplicateMusicHandler:()=>IT,registerDefaultMusicHandlers:()=>nur});function nur(){for(const{name:e,aliases:t,factory:r}of iur){const n=!Gp.supports(e),o=(t??[]).filter(i=>!Gp.supports(i));if(!(!n&&o.length===0))try{let i;if(n||(i=Gp.getHandler(e)),!i&&(i=r(),!i.isConfigured()))continue;n&&Gp.registerHandler(e,i);for(const s of o)Gp.registerHandler(s,i)}catch(i){h.debug(`[music] ${e} auto-registration skipped: ${i instanceof Error?i.message:String(i)}`)}}}var our,iur,tde=S({"src/lib/music/index.ts"(){"use strict";jv(),z(),qp(),qp(),Hcr(),Kcr(),Ycr(),rur(),Hcr(),Kcr(),Ycr(),rur(),our={beatoven:()=>new kT,"elevenlabs-music":()=>new xT,lyria:()=>new AT,replicate:()=>new IT},iur=op.filter(e=>e.kind==="music").map(e=>{const t=our[e.name];if(!t)throw new Error(`[music] no handler factory for catalog entry "${e.name}"`);return{name:e.name,aliases:e.aliases,factory:t}})}}),sur={};ce(sur,{AVATAR_ERROR_CODES:()=>xt,AvatarError:()=>St,AvatarProcessor:()=>jp});var xt,St,jp,Kh=S({"src/lib/utils/avatarProcessor.ts"(){"use strict";Zn(),et(),z(),bw(),xt={PROVIDER_NOT_SUPPORTED:"AVATAR_PROVIDER_NOT_SUPPORTED",PROVIDER_NOT_CONFIGURED:"AVATAR_PROVIDER_NOT_CONFIGURED",GENERATION_FAILED:"AVATAR_GENERATION_FAILED",POLL_TIMEOUT:"AVATAR_POLL_TIMEOUT",INVALID_INPUT:"AVATAR_INVALID_INPUT",AUDIO_REQUIRED:"AVATAR_AUDIO_REQUIRED",IMAGE_REQUIRED:"AVATAR_IMAGE_REQUIRED",AUDIO_TOO_LONG:"AVATAR_AUDIO_TOO_LONG"},St=class extends Me{constructor(e){super({code:e.code,message:e.message,category:e.category??"execution",severity:e.severity??"high",retriable:e.retriable??!1,context:e.context,originalError:e.originalError}),this.name="AvatarError"}},jp=class{static registry=new Fg("AvatarProcessor");static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),h.debug(`[AvatarProcessor] Registered avatar handler: ${r}`)}static supports(e){return this.registry.supports(e)}static listProviders(){return this.registry.list()}static getHandler(e){return this.registry.get(e)}static clearHandlers(){this.registry.clear()}static buildSpanAttributes(e,t){return{"avatar.operation":"generate","avatar.provider":e,"avatar.quality":t.quality,"avatar.format":t.format,"avatar.has_text":t.text!==void 0,"avatar.has_audio":t.audio!==void 0}}static async generate(e,t){const r=Ce.createSpan("media.generation","avatar.generate",this.buildSpanAttributes(e,t));try{if(!t.image)throw new St({code:xt.IMAGE_REQUIRED,message:"Avatar generation requires an `image` (Buffer, path, or URL)",category:"validation",severity:"medium",retriable:!1,context:{provider:e}});if(!t.audio&&!t.text)throw new St({code:xt.INVALID_INPUT,message:"Avatar generation requires either `audio` (a Buffer/URL) or `text` (to be TTS'd by the provider).",category:"validation",severity:"high",retriable:!1,context:{provider:e}});const n=this.getHandler(e);if(!n)throw new St({code:xt.PROVIDER_NOT_SUPPORTED,message:`Avatar provider "${e}" is not registered. Available: ${this.listProviders().join(", ")}`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!n.isConfigured())throw new St({code:xt.PROVIDER_NOT_CONFIGURED,message:`Avatar provider "${e}" is not configured. Set the required credentials.`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});h.debug(`[AvatarProcessor] Starting avatar generation with provider: ${e}`);const o=await n.generate(t),i=Ce.endSpan(r,1);return rt().recordSpan(i),h.info(`[AvatarProcessor] Generated ${o.size} bytes (${e})`),o}catch(n){const o=Ce.endSpan(r,2,n instanceof Error?n.message:String(n));if(rt().recordSpan(o),n instanceof St)throw n;const i=n instanceof Error?n.message:String(n);throw new St({code:xt.GENERATION_FAILED,message:`Avatar generation failed for provider "${e}": ${i}`,category:"execution",severity:"high",retriable:!0,context:{provider:e},originalError:n instanceof Error?n:void 0})}}}}}),aur,rde,lur,cur,RT,uur=S({"src/lib/avatar/providers/DIDAvatar.ts"(){"use strict";z(),Ft(),Kh(),OC(),Ta(),aur="https://api.d-id.com",rde=3e4,lur=3e3,cur=5*6e4,RT=class{maxAudioDurationSeconds=60;supportedFormats=["mp4"];apiKey;baseUrl;constructor(e){const t=(e??process.env.DID_API_KEY??process.env.D_ID_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.DID_BASE_URL??process.env.D_ID_BASE_URL??aur).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new St({code:xt.PROVIDER_NOT_CONFIGURED,message:"DID_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});if(!e.audio&&!e.text)throw new St({code:xt.AUDIO_REQUIRED,message:"D-ID requires either `audio` (Buffer/path) or `text` (with voice id) to drive the talk",category:"validation",severity:"medium",retriable:!1});const t=Date.now(),r=await this.uploadImage(e.image),n=e.audio?await this.uploadAudio(e.audio):void 0,o=await this.submitTalk(e,r,n),i=await this.pollUntilDone(o,e.timeout??cur,e.abortSignal);if(!i.result_url)throw new St({code:xt.GENERATION_FAILED,message:`D-ID talk ${o} completed but no result_url returned`,category:"execution",severity:"high",retriable:!1,context:{talkId:o,completed:i}});try{await PC(i.result_url)}catch(l){throw new St({code:xt.GENERATION_FAILED,message:`D-ID result_url rejected as unsafe: ${l instanceof Error?l.message:String(l)}`,category:"validation",severity:"high",retriable:!1,context:{talkId:o,url:i.result_url}})}const s=await this.downloadResult(i.result_url),a=Date.now()-t;return h.info(`[DIDAvatar] Generated ${s.length} bytes in ${a}ms \u2014 talk ${o}`),{buffer:s,format:"mp4",size:s.length,duration:i.duration,provider:"d-id",metadata:{latency:a,provider:"d-id",jobId:o}}}async uploadImage(e){if(typeof e=="string"&&/^https:\/\//.test(e))return e;const t=await this.resolveBuffer(e),r=new FormData;r.append("image",new Blob([new Uint8Array(t)],{type:this.detectImageMime(t)}),"source.png");const n=await this.fetchWithTimeout(`${this.baseUrl}/images`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`},body:r}),o=await this.assertOk(n,"image upload");if(!o.url)throw new St({code:xt.GENERATION_FAILED,message:"D-ID image upload succeeded but returned no URL",category:"execution",severity:"high",retriable:!1});return o.url}async uploadAudio(e){if(typeof e=="string"&&/^https:\/\//.test(e))return e;const t=await this.resolveBuffer(e),r=this.detectAudioType(t),o={mp3:"mp3",mpeg:"mp3",wav:"wav",ogg:"ogg",mp4:"m4a"}[r]??"mp3",i=new FormData;i.append("audio",new Blob([new Uint8Array(t)],{type:`audio/${r}`}),`narration.${o}`);const s=await this.fetchWithTimeout(`${this.baseUrl}/audios`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`},body:i}),a=await this.assertOk(s,"audio upload");if(!a.url)throw new St({code:xt.GENERATION_FAILED,message:"D-ID audio upload succeeded but returned no URL",category:"execution",severity:"high",retriable:!1});return a.url}async submitTalk(e,t,r){const n=r?{type:"audio",audio_url:r}:{type:"text",input:e.text,provider:{type:"microsoft",voice_id:e.voice??"en-US-JennyNeural"}},o={source_url:t,script:n,config:{result_format:"mp4",stitch:!0}},i=await this.fetchWithTimeout(`${this.baseUrl}/talks`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(o)}),s=await this.assertOk(i,"talk submit");if(!s.id)throw new St({code:xt.GENERATION_FAILED,message:"D-ID talk submit returned no id",category:"execution",severity:"high",retriable:!1});return s.id}async pollUntilDone(e,t,r){const n=Date.now();for(;Date.now()-n<t;){if(r?.aborted)throw new St({code:xt.GENERATION_FAILED,message:`D-ID poll for talk ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{talkId:e}});const o=await this.fetchWithTimeout(`${this.baseUrl}/talks/${e}`,{method:"GET",headers:{Authorization:`Basic ${this.apiKey}`}},r),i=await this.assertOk(o,"talk status");if(i.status==="done")return i;if(i.status==="error"||i.status==="rejected")throw new St({code:xt.GENERATION_FAILED,message:`D-ID talk ${e} ${i.status}: ${i.error?.description??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{talkId:e,status:i.status,error:i.error}});await new Promise((s,a)=>{const l=()=>{clearTimeout(c),a(new St({code:xt.GENERATION_FAILED,message:`D-ID poll for talk ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{talkId:e}}))},c=setTimeout(()=>{r?.removeEventListener("abort",l),s()},lur);r?.addEventListener("abort",l,{once:!0})})}throw new St({code:xt.POLL_TIMEOUT,message:`D-ID talk ${e} did not complete within ${Math.round(t/1e3)}s`,category:"timeout",severity:"medium",retriable:!0,context:{talkId:e}})}async downloadResult(e){const t=await this.fetchWithTimeout(e,{method:"GET"});if(!t.ok)throw new St({code:xt.GENERATION_FAILED,message:`D-ID result download failed: ${t.status}`,category:"network",severity:"medium",retriable:t.status>=500,context:{status:t.status,url:e}});try{return await l0(t,c0,"D-ID result")}catch(r){throw new St({code:xt.GENERATION_FAILED,message:`D-ID result download rejected: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:r instanceof Error?r:void 0})}}async resolveBuffer(e){if(Buffer.isBuffer(e))return e;if(!/^https:\/\//.test(e))throw new St({code:xt.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await PC(e)}catch(n){throw new St({code:xt.INVALID_INPUT,message:`Unsafe URL rejected: ${n instanceof Error?n.message:String(n)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=await this.fetchWithTimeout(e,{method:"GET"});if(!t.ok)throw new St({code:xt.INVALID_INPUT,message:`Failed to fetch input from ${e}: ${t.status}`,category:"network",severity:"medium",retriable:t.status>=500,context:{url:e,status:t.status}});const r=Math.max(Vh,Hh);try{return await l0(t,r,"D-ID input")}catch(n){throw new St({code:xt.INVALID_INPUT,message:`D-ID input download rejected: ${n instanceof Error?n.message:String(n)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:n instanceof Error?n:void 0})}}detectImageMime(e){return e.length<4?"image/jpeg":e[0]===137&&e[1]===80?"image/png":e[0]===255&&e[1]===216?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":"image/jpeg"}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}async fetchWithTimeout(e,t,r){const n=new AbortController,o=setTimeout(()=>n.abort(),rde),i=()=>n.abort();r?.addEventListener("abort",i,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?r?.aborted?new St({code:xt.GENERATION_FAILED,message:`D-ID request to ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,originalError:s}):new St({code:xt.GENERATION_FAILED,message:`D-ID request to ${e} timed out after ${rde/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:s}):s}finally{r?.removeEventListener("abort",i),clearTimeout(o)}}async assertOk(e,t){if(e.ok)return e.json();const r=await e.text(),n=e.status===408||e.status===429||e.status>=500;throw new St({code:xt.GENERATION_FAILED,message:`D-ID ${t} failed: ${e.status} \u2014 ${gr(r,500)}`,category:n?"network":"execution",severity:"high",retriable:n,context:{status:e.status,label:t}})}}}}),dur,F$,pur,nde,MT,mur=S({"src/lib/avatar/providers/HeyGenAvatar.ts"(){"use strict";Kh(),z(),Ft(),Md(),Ta(),dur="https://api.heygen.com/v2",F$=3e4,pur=5e3,nde=5*6e4,MT=class{maxAudioDurationSeconds=300;supportedFormats=["mp4"];apiKey;baseUrl;constructor(e){const t=(e??process.env.HEYGEN_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.HEYGEN_BASE_URL??dur).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new St({code:xt.PROVIDER_NOT_CONFIGURED,message:"HEYGEN_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});if(!e.text&&!e.audio)throw new St({code:xt.AUDIO_REQUIRED,message:"HeyGen requires either `text` or `audio` to drive the avatar",category:"validation",severity:"medium",retriable:!1});const t=Date.now(),r=e.abortSignal,n=await this.submitVideo(e),o=await this.pollUntilComplete(n,r),i=await this.download(o),s=Date.now()-t;return h.info(`[HeyGenAvatar] Generated ${i.length} bytes in ${s}ms \u2014 video ${n}`),{buffer:i,format:"mp4",size:i.length,provider:"heygen",metadata:{latency:s,provider:"heygen",jobId:n}}}async submitVideo(e){const t=e,r=t.avatarId??(typeof e.image=="string"&&/^[a-zA-Z0-9_-]{20,}$/.test(e.image)?e.image:void 0);if(!r)throw new St({code:xt.INVALID_INPUT,message:"HeyGen requires `avatarId` (HeyGen avatar catalog id). Pass via options.avatarId or as options.image with a valid HeyGen id.",category:"validation",severity:"medium",retriable:!1});if(e.audio!==void 0){if(Buffer.isBuffer(e.audio))throw new St({code:xt.INVALID_INPUT,message:"HeyGen requires a publicly accessible audio URL; got a binary Buffer. Upload the audio to a hosted location and pass the HTTPS URL instead.",category:"validation",severity:"medium",retriable:!1});if(typeof e.audio!="string"||!/^https?:\/\//i.test(e.audio))throw new St({code:xt.INVALID_INPUT,message:"HeyGen requires a publicly accessible HTTPS audio URL; got an unsupported audio input type. Upload the audio to a hosted location and pass the HTTPS URL instead.",category:"validation",severity:"medium",retriable:!1})}const n=e.audio?{type:"audio",audio_url:e.audio}:{type:"text",input_text:e.text,voice_id:e.voice??"1bd001e7e50f421d891986aad5158bc8"},o={video_inputs:[{character:{type:"avatar",avatar_id:r,avatar_style:"normal"},voice:n,background:{type:"color",value:t.backgroundColor??"#FFFFFF"}}],dimension:{width:t.width??1280,height:t.height??720}},i=await this.fetchWithTimeout(`${this.baseUrl}/video/generate`,{method:"POST",headers:{"X-API-Key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok){const l=await i.text(),c=i.status===408||i.status===429||i.status>=500;throw new St({code:xt.GENERATION_FAILED,message:`HeyGen submit failed: ${i.status} \u2014 ${gr(l,500)}`,category:c?"network":"execution",severity:"high",retriable:c,context:{status:i.status}})}const s=await i.json(),a=s.data?.video_id;if(!a)throw new St({code:xt.GENERATION_FAILED,message:"HeyGen submit response missing video_id",category:"execution",severity:"high",retriable:!1,context:{response:s}});return a}async pollUntilComplete(e,t){const r=Date.now(),n=this.baseUrl.replace(/\/v2$/,"/v1");for(;Date.now()-r<nde;){if(t?.aborted)throw new St({code:xt.GENERATION_FAILED,message:`HeyGen poll for video ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{videoId:e}});const o=await this.fetchWithTimeout(`${n}/video_status.get?video_id=${e}`,{method:"GET",headers:{"X-API-Key":this.apiKey}},t);if(!o.ok){const s=await o.text();throw new St({code:xt.GENERATION_FAILED,message:`HeyGen poll failed: ${o.status} \u2014 ${gr(s,500)}`,category:"network",severity:"medium",retriable:o.status>=500,context:{status:o.status,videoId:e}})}const i=await o.json();if(i.data?.status==="completed"){const s=i.data.video_url;if(!s)throw new St({code:xt.GENERATION_FAILED,message:`HeyGen video ${e} completed but no URL returned`,category:"execution",severity:"high",retriable:!1,context:{videoId:e,data:i}});return s}if(i.data?.status==="failed")throw new St({code:xt.GENERATION_FAILED,message:`HeyGen video ${e} failed: ${i.data?.error?.message??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{videoId:e,data:i}});await new Promise((s,a)=>{const l=()=>{clearTimeout(c),a(new St({code:xt.GENERATION_FAILED,message:`HeyGen poll for video ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{videoId:e}}))},c=setTimeout(()=>{t?.removeEventListener("abort",l),s()},pur);t?.addEventListener("abort",l,{once:!0})})}throw new St({code:xt.POLL_TIMEOUT,message:`HeyGen video ${e} did not complete within ${nde/1e3}s`,category:"timeout",severity:"medium",retriable:!0,context:{videoId:e}})}async download(e){try{return await zp(e,{maxBytes:c0,label:"HeyGen video",timeoutMs:F$})}catch(t){throw new St({code:xt.GENERATION_FAILED,message:`HeyGen video download rejected: ${t instanceof Error?t.message:String(t)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:t instanceof Error?t:void 0})}}async fetchWithTimeout(e,t,r){const n=new AbortController;let o=!1;const i=setTimeout(()=>{o=!0,n.abort()},F$),s=()=>n.abort();r?.addEventListener("abort",s,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?r?.aborted?new St({code:xt.GENERATION_FAILED,message:`HeyGen request to ${e} was aborted by the caller`,category:"network",severity:"medium",retriable:!1,originalError:a}):o?new St({code:xt.GENERATION_FAILED,message:`HeyGen request to ${e} timed out after ${F$/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:a}):new St({code:xt.GENERATION_FAILED,message:`HeyGen request to ${e} was aborted`,category:"network",severity:"high",retriable:!0,originalError:a}):a}finally{r?.removeEventListener("abort",s),clearTimeout(i)}}}}}),hur,PT,fur=S({"src/lib/avatar/providers/ReplicateAvatar.ts"(){"use strict";Kh(),z(),D$(),L$(),Ta(),OC(),hur="douwantech/musetalk:5501004e78525e4bbd9fa20d1e75ad51fddce5a274bec07b9b16d685e34eeaf8",PT=class{maxAudioDurationSeconds=60;supportedFormats=["mp4"];isConfigured(){return Wh()!==null}async generate(e){const t=Wh();if(!t)throw new St({code:xt.PROVIDER_NOT_CONFIGURED,message:"REPLICATE_API_TOKEN not configured",category:"configuration",severity:"high",retriable:!1});if(!e.audio)throw new St({code:xt.AUDIO_REQUIRED,message:"Replicate avatar handler (MuseTalk) requires `audio` (Buffer or path); text-only is not supported. Use D-ID for text-driven talks or chain TTS + Replicate.",category:"validation",severity:"medium",retriable:!1});const r=Date.now(),n=e.model??hur,o=await this.resolveBuffer(e.image,Hh,"Replicate avatar reference image"),i=await this.resolveBuffer(e.audio,Vh,"Replicate avatar reference audio"),s=`data:image/${this.detectImageType(o)};base64,${o.toString("base64")}`,a=`data:audio/${this.detectAudioType(i)};base64,${i.toString("base64")}`;let l;try{l=await UC(t,{model:n,input:{image:s,audio:a,bbox_shift:0,fps:25}})}catch(d){throw new St({code:xt.GENERATION_FAILED,message:`Replicate avatar generation failed: ${d instanceof Error?d.message:String(d)}`,category:"execution",severity:"high",retriable:!0,context:{model:n},originalError:d instanceof Error?d:void 0})}let c;try{c=await N$(l,c0)}catch(d){throw new St({code:xt.GENERATION_FAILED,message:`Replicate avatar download failed: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"medium",retriable:!0,context:{predictionId:l.id},originalError:d instanceof Error?d:void 0})}const u=Date.now()-r;return h.info(`[ReplicateAvatar] Generated ${c.length} bytes in ${u}ms \u2014 model ${n}`),{buffer:c,format:"mp4",size:c.length,provider:"replicate",metadata:{latency:u,provider:"replicate",model:n,jobId:l.id}}}async resolveBuffer(e,t=Hh,r="Replicate avatar input"){if(Buffer.isBuffer(e)){if(e.length>t)throw new St({code:xt.INVALID_INPUT,message:`${r} too large: ${e.length} bytes exceeds ${t}`,category:"validation",severity:"high",retriable:!1});return e}if(!/^https:\/\//.test(e))throw new St({code:xt.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await PC(e)}catch(a){throw new St({code:xt.INVALID_INPUT,message:`Unsafe URL rejected: ${a instanceof Error?a.message:String(a)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const n=6e4,o=new AbortController,i=setTimeout(()=>o.abort(),n);let s;try{s=await fetch(e,{signal:o.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new St({code:xt.INVALID_INPUT,message:`Replicate avatar input fetch timed out after ${n/1e3}s: ${e}`,category:"network",severity:"medium",retriable:!0}):a}finally{clearTimeout(i)}if(!s.ok)throw new St({code:xt.INVALID_INPUT,message:`Failed to fetch ${e}: ${s.status}`,category:"network",severity:"medium",retriable:s.status>=500});try{return await l0(s,t,r)}catch(a){throw new St({code:xt.INVALID_INPUT,message:`${r} too large: ${a instanceof Error?a.message:String(a)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}detectImageType(e){return e.length<4?"jpeg":e[0]===137&&e[1]===80?"png":e[0]===255&&e[1]===216?"jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"webp":"jpeg"}}}}),ode={};ce(ode,{AVATAR_ERROR_CODES:()=>xt,AvatarError:()=>St,AvatarProcessor:()=>jp,DIDAvatar:()=>RT,DIDAvatarHandler:()=>RT,HeyGenAvatar:()=>MT,HeyGenAvatarHandler:()=>MT,ReplicateAvatar:()=>PT,ReplicateAvatarHandler:()=>PT,registerDefaultAvatarHandlers:()=>gur});function gur(){for(const{name:e,aliases:t,factory:r}of vur){const n=!jp.supports(e),o=(t??[]).filter(i=>!jp.supports(i));if(!(!n&&o.length===0))try{let i;if(n||(i=jp.getHandler(e)),!i&&(i=r(),!i.isConfigured()))continue;n&&jp.registerHandler(e,i);for(const s of o)jp.registerHandler(s,i)}catch(i){h.debug(`[avatar] ${e} auto-registration skipped: ${i instanceof Error?i.message:String(i)}`)}}}var yur,vur,ide=S({"src/lib/avatar/index.ts"(){"use strict";jv(),z(),Kh(),Kh(),uur(),mur(),fur(),uur(),mur(),fur(),yur={"d-id":()=>new RT,heygen:()=>new MT,replicate:()=>new PT},vur=op.filter(e=>e.kind==="avatar").map(e=>{const t=yur[e.name];if(!t)throw new Error(`[avatar] no handler factory for catalog entry "${e.name}"`);return{name:e.name,aliases:e.aliases,factory:t}})}}),OT,$$,sde=S({"src/lib/mcp/elicitation/elicitationManager.ts"(){"use strict";eo(),Bt(),z(),OT=class extends fn{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(const[t,r]of this.pendingRequests)r.settled||(r.settled=!0,this.handleDisabled(r.request,r.resolve),r.timer&&clearTimeout(r.timer),this.pendingRequests.delete(t))}isEnabled(){return this.config.enabled}async request(e){const t={...e,id:e.id??it()};if(!this.config.enabled)return this.handleDisabledRequest(t);const r=t.timeout??this.config.defaultTimeout;return new Promise(n=>{const o=setTimeout(()=>{const i=this.pendingRequests.get(t.id);!i||i.settled||(i.settled=!0,this.handleTimeout(t,n))},r);this.pendingRequests.set(t.id,{request:t,resolve:n,timer:o,settled:!1}),this.emit("elicitationRequested",t),Promise.resolve().then(()=>this.config.handler(t)).then(i=>{const s=this.pendingRequests.get(t.id);!s||s.settled||(s.settled=!0,clearTimeout(o),this.pendingRequests.delete(t.id),this.emit("elicitationResponded",i),n(i))}).catch(i=>{const s=this.pendingRequests.get(t.id);if(!s||s.settled)return;s.settled=!0,clearTimeout(o),this.pendingRequests.delete(t.id);const a={requestId:t.id,responded:!1,error:i instanceof Error?i.message:String(i),timestamp:Date.now()};this.emit("elicitationError",{request:t,error:i}),n(a)})})}async confirm(e,t){const r={type:"confirmation",message:e,toolName:t?.toolName??"unknown",serverId:t?.serverId,confirmLabel:t?.confirmLabel,cancelLabel:t?.cancelLabel,timeout:t?.timeout};return(await this.request(r)).value===!0}async getText(e,t){const r={type:"text",message:e,toolName:t?.toolName??"unknown",placeholder:t?.placeholder,defaultValue:t?.defaultValue,timeout:t?.timeout};return(await this.request(r)).value}async select(e,t,r){const n={type:"select",message:e,toolName:r?.toolName??"unknown",options:t,timeout:r?.timeout};return(await this.request(n)).value}async multiSelect(e,t,r){const n={type:"multiselect",message:e,toolName:r?.toolName??"unknown",options:t,timeout:r?.timeout,minSelections:r?.minSelections,maxSelections:r?.maxSelections};return(await this.request(n)).value}async form(e,t,r){const n={type:"form",message:e,toolName:r?.toolName??"unknown",serverId:r?.serverId,fields:t,submitLabel:r?.submitLabel,timeout:r?.timeout};return(await this.request(n)).value}async getSecret(e,t){const r={type:"secret",message:e,toolName:t?.toolName??"unknown",hint:t?.hint,timeout:t?.timeout};return(await this.request(r)).value}cancel(e,t){const r=this.pendingRequests.get(e);if(r){if(r.settled)return;r.settled=!0,r.timer&&clearTimeout(r.timer);const n={requestId:e,responded:!1,cancelled:!0,error:t,timestamp:Date.now()};r.resolve(n),this.pendingRequests.delete(e),this.emit("elicitationCancelled",{requestId:e,reason:t})}}async defaultHandler(e){return h.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);const r={requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()};this.emit("elicitationTimeout",{request:e}),t(r)}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(const[t]of this.pendingRequests)this.cancel(t,e??"Cleared")}},$$=new OT}}),wur={};ce(wur,{ElicitationManager:()=>OT,globalElicitationManager:()=>$$});var bur=S({"src/lib/mcp/elicitation/index.ts"(){"use strict";sde()}});function yu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ja(e,t){const r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function ade(e,t){const r=e[t];return Array.isArray(r)?r:[]}function BC(e){return e.filter(t=>t!==void 0)}function rvn(e){return e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e)}function nvn(e){if(e.type!=="official"&&e.type!=="custom")return;const t=e.url??(e.type==="official"?kur:"");let r;try{r=new URL(t)}catch{return}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.username!==""||r.password!==""||e.authToken&&r.protocol==="http:"&&!rvn(r.hostname))return;const n=r.pathname.replace(/\/+$/,""),o=n.endsWith(lde)?n:`${n}${lde}`;return{config:e,apiBase:`${r.origin}${o}`}}function ovn(e){if(!yu(e))return;const t=Ja(e,"name");return t===void 0?void 0:{name:t,isRequired:e.isRequired===!0,isSecret:e.isSecret===!0}}function Tur(e){if(!yu(e))return;const t=Ja(e,"type");if(t===void 0)return;const r=Ja(e,"url");return r===void 0?{type:t}:{type:t,url:r}}function ivn(e){if(!yu(e))return;const t=Ja(e,"registryType"),r=Ja(e,"identifier");if(t===void 0||r===void 0)return;const n=Ja(e,"version"),o=Tur(e.transport);return{registryType:t,identifier:r,...n===void 0?{}:{version:n},...o===void 0?{}:{transport:o},environmentVariables:BC(ade(e,"environmentVariables").map(ovn))}}function svn(e){if(!yu(e))return;const t=Ja(e,"name");if(t===void 0)return;const r=yu(e.repository)?e.repository:void 0,n=r===void 0?void 0:Ja(r,"url"),o=Ja(e,"websiteUrl");return{name:t,description:Ja(e,"description")??"",version:Ja(e,"version")??"",...n===void 0?{}:{repositoryUrl:n},...o===void 0?{}:{websiteUrl:o},packages:BC(ade(e,"packages").map(ivn)),remotes:BC(ade(e,"remotes").map(Tur))}}function _ur(e){if(!yu(e))return;const t=svn(e.server);if(t===void 0)return;const r=yu(e._meta)?e._meta:void 0,n=r!==void 0?r[xur]:void 0,o=yu(n)?Ja(n,"status"):void 0,i=yu(n)?Ja(n,"updatedAt"):void 0;return{server:t,...o===void 0?{}:{status:o},...i===void 0?{}:{updatedAt:i}}}function avn(e){if(!yu(e)||!Array.isArray(e.servers))throw new Error("registry list response has no servers array");const t=yu(e.metadata)?e.metadata:void 0,r=t===void 0?void 0:Ja(t,"nextCursor");return{records:BC(e.servers.map(_ur)),...r===void 0?{}:{nextCursor:r}}}function Eur(e){switch(e){case"stdio":return"stdio";case"streamable-http":return"http";case"sse":return"sse";default:return}}function lvn(e){if(!(e.registryType!=="npm"||e.identifier.length>Cur||!Aur.test(e.identifier)))return e.version===void 0?e.identifier:e.version.length<=Rur&&Iur.test(e.version)?`${e.identifier}@${e.version}`:void 0}function Sur(e,t){const{server:r}=e,n=r.packages.map(l=>({pkg:l,spec:lvn(l)})).find(l=>l.spec!==void 0),o=Array.from(new Set(BC([...r.packages.map(l=>l.transport===void 0?void 0:Eur(l.transport.type)),...r.remotes.map(l=>Eur(l.type))]))),i=n===void 0?[]:n.pkg.environmentVariables.filter(l=>l.isRequired).map(l=>l.name),s=r.remotes.flatMap(l=>l.url===void 0?[]:[{type:l.type,url:l.url}]),a={source:"remote-registry",registry:t,...e.status===void 0?{}:{registryStatus:e.status},packages:r.packages.map(l=>({registryType:l.registryType,identifier:l.identifier,...l.version===void 0?{}:{version:l.version}})),remotes:s};return{id:r.name,name:r.name,description:r.description,version:r.version,...r.websiteUrl===void 0?{}:{homepage:r.websiteUrl},...r.repositoryUrl===void 0?{}:{repository:r.repositoryUrl},...n===void 0?{}:{npmPackage:n.pkg.identifier,command:"npx",args:["-y",n.spec],installCommand:`npx -y ${n.spec}`},...i.length===0?{}:{requiredEnvVars:i},...o.length===0?{}:{transports:o},...e.updatedAt===void 0?{}:{lastUpdated:e.updatedAt},verified:!1,metadata:a}}var kur,lde,xur,Aur,Cur,Iur,Rur,cvn=S({"src/lib/mcp/mcpRegistryRemote.ts"(){"use strict";kur="https://registry.modelcontextprotocol.io",lde="/v0.1",xur="io.modelcontextprotocol.registry/official",Aur=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,Cur=214,Iur=/^[0-9A-Za-z][0-9A-Za-z.+_~-]*$/,Rur=128}}),Mur={};ce(Mur,{MCPRegistryClient:()=>U$,getAllWellKnownServers:()=>Our,getWellKnownServer:()=>Pur,globalMCPRegistryClient:()=>ude});function Pur(e){return zC.find(t=>t.id===e)}function Our(){return[...zC]}var Dur,Nur,cde,Lur,zC,U$,ude,Fur=S({"src/lib/mcp/mcpRegistryClient.ts"(){"use strict";eo(),z(),cvn(),Dur=100,Nur=5,cde=8*1024*1024,Lur=500,zC=[{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}],U$=class extends fn{config;cache=new Map;customEntries=new Map;constructor(e={}){super(),this.config={registries:[...e.registries??[{type:"official",enableCache:!0}]],remoteLookup:e.remoteLookup??!1,enableCache:e.enableCache??!0,defaultCacheTTL:e.defaultCacheTTL??36e5,timeout:e.timeout??1e4,userAgent:e.userAgent??"NeuroLink-MCP-Registry-Client/1.0"}}async search(e={}){const{query:t,categories:r,tags:n,transport:o,verifiedOnly:i=!1,sortBy:s="downloads",sortDirection:a="desc",limit:l=25,offset:c=0}=e,u=Math.max(1,l),d=Math.max(0,c);let m=[...t?await this.collectEntries(t):await this.getAllEntries()];if(t){const g=t.toLowerCase();m=m.filter(y=>y.name.toLowerCase().includes(g)||y.description.toLowerCase().includes(g)||y.tags?.some(v=>v.toLowerCase().includes(g)))}r?.length&&(m=m.filter(g=>g.categories?.some(y=>r.includes(y)))),n?.length&&(m=m.filter(g=>g.tags?.some(y=>n.includes(y)))),o&&(m=m.filter(g=>g.transports?.includes(o))),i&&(m=m.filter(g=>g.verified)),m.sort((g,y)=>{let v=0;switch(s){case"name":v=g.name.localeCompare(y.name);break;case"downloads":v=(g.downloads??0)-(y.downloads??0);break;case"stars":v=(g.stars??0)-(y.stars??0);break;case"lastUpdated":v=(g.lastUpdated??"").localeCompare(y.lastUpdated??"");break}return a==="desc"?-v:v});const f=m.length;return m=m.slice(d,d+u),{entries:m,totalCount:f,page:Math.floor(d/u)+1,pageSize:u,hasMore:d+m.length<f}}async getEntry(e){if(this.customEntries.has(e))return this.customEntries.get(e);const t=zC.find(r=>r.id===e);if(t)return t;if(this.config.remoteLookup&&!(e===""||e==="."||e===".."))for(const r of this.getRemoteTargets()){const n=await this.fetchRemoteEntry(r,e);if(n)return n}}async getAllEntries(){return this.collectEntries()}async collectEntries(e){const t=e===void 0||!this.config.remoteLookup?"all-entries":`all-entries:${e.toLowerCase()}`,r=this.config.remoteLookup?this.getRemoteTargets():[],n=this.config.enableCache&&r.every(u=>this.isRemoteCacheEnabled(u)),o=Math.min(this.config.defaultCacheTTL,...r.map(u=>u.config.cacheTTL??this.config.defaultCacheTTL)),i=n?this.readCache(t,o):void 0;if(i)return i;const s=new Set(this.customEntries.keys()),a=[...zC.filter(u=>!s.has(u.id)),...Array.from(this.customEntries.values())];let l=a,c=!0;if(this.config.remoteLookup){const u=await Promise.all(r.map(m=>this.fetchRemoteList(m,e))),d=new Set(a.map(m=>m.id)),p=[];for(const m of u){c=c&&m.ok;for(const f of m.entries)d.has(f.id)||(d.add(f.id),p.push(f))}l=[...a,...p]}return n&&c&&this.writeCache(t,l),l}getRemoteTargets(){return this.config.registries.flatMap(e=>{const t=nvn(e);return t===void 0?(ue.debug(`[MCPRegistryClient] Skipping registry of type "${e.type}": not queryable (unsupported type, missing or unusable URL, or a bearer token on plain http to a non-loopback host)`),[]):[t]})}async fetchRemoteEntry(e,t){const r=`remote-entry:${e.apiBase}:${t}`,n=this.readRemoteCache(r,e);if(n)return n;try{const o=await this.requestJson(e,`/servers/${encodeURIComponent(t)}/versions/latest`);if(o.body===void 0)return;const i=_ur(o.body);if(i===void 0||i.status==="deleted"||i.server.name.toLowerCase()!==t.toLowerCase())throw new Error("registry returned no record for the requested server");const s=Sur(i,e.apiBase);return this.writeRemoteCache(r,s,e),s}catch(o){this.reportRemoteError(e,"getEntry",o);return}}async fetchRemoteList(e,t){const r=`remote-list:${e.apiBase}:${(t??"").toLowerCase()}`,n=this.readRemoteCache(r,e);if(n)return{entries:n,ok:!0};try{const o=e.config.maxPages,i=o!==void 0&&Number.isFinite(o)?Math.max(1,Math.floor(o)):Nur,s=[],a=new Set;let l;for(let c=0;c<i;c++){const u=new URLSearchParams({version:"latest",limit:String(Dur)});t&&u.set("search",t),l&&u.set("cursor",l);const d=await this.requestJson(e,"/servers",u),{records:p,nextCursor:m}=avn(d.body);if(s.push(...p.filter(f=>f.status!=="deleted").map(f=>Sur(f,e.apiBase))),m===void 0||a.has(m))break;if(c===i-1){ue.debug(`[MCPRegistryClient] ${e.apiBase}: stopped after ${i} page(s); more servers are available`);break}a.add(m),l=m}return this.writeRemoteCache(r,s,e),{entries:s,ok:!0}}catch(o){return this.reportRemoteError(e,"list",o),{entries:[],ok:!1}}}async requestJson(e,t,r){const n=new URL(`${e.apiBase}${t}`);r?.forEach((s,a)=>n.searchParams.set(a,s));const o={Accept:"application/json","User-Agent":this.config.userAgent,...e.config.authToken?{Authorization:`Bearer ${e.config.authToken}`}:{}},i=await globalThis.fetch(n,{method:"GET",headers:o,signal:AbortSignal.timeout(e.config.timeout??this.config.timeout)});if(i.status===404)return await i.body?.cancel(),{body:void 0};if(!i.ok)throw await i.body?.cancel(),new Error(`registry responded with HTTP ${i.status}`);return{body:await this.readBoundedJson(i)}}async readBoundedJson(e){const t=[];let r=0;if(e.body){const n=e.body.getReader();for(;;){const{done:o,value:i}=await n.read();if(o)break;if(r+=i.byteLength,r>cde)throw await n.cancel(),new Error(`registry response exceeds ${cde} bytes`);t.push(i)}}return JSON.parse(Buffer.concat(t).toString("utf8"))}reportRemoteError(e,t,r){const n=r instanceof Error?r.message:String(r),o=r instanceof Error?r.cause:void 0,i=typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0,s=i===void 0?n:`${n} (${i})`;ue.debug(`[MCPRegistryClient] ${t} failed for ${e.apiBase}: ${s}`);try{this.emit("registryError",{registry:e.apiBase,operation:t,message:s})}catch(a){ue.debug(`[MCPRegistryClient] registryError listener threw: ${String(a)}`)}}readCache(e,t){const r=this.cache.get(e);return r&&Date.now()-r.timestamp<t?r.data:void 0}readRemoteCache(e,t){return this.isRemoteCacheEnabled(t)?this.readCache(e,t.config.cacheTTL??this.config.defaultCacheTTL):void 0}writeRemoteCache(e,t,r){this.isRemoteCacheEnabled(r)&&this.writeCache(e,t)}isRemoteCacheEnabled(e){return this.config.enableCache&&(e.config.enableCache??!0)}writeCache(e,t){if(!this.cache.has(e)&&this.cache.size>=Lur){const r=this.cache.keys().next();r.done||this.cache.delete(r.value)}this.cache.set(e,{data:t,timestamp:Date.now()})}async getByCategory(e){return(await this.getAllEntries()).filter(r=>r.categories?.includes(e))}async getByTag(e){return(await this.getAllEntries()).filter(r=>r.tags?.includes(e))}async getCategories(){const e=await this.getAllEntries(),t=new Set;for(const r of e)for(const n of r.categories??[])t.add(n);return Array.from(t).sort()}async getTags(){const e=await this.getAllEntries(),t=new Set;for(const r of e)for(const n of r.tags??[])t.add(n);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){const t=this.customEntries.delete(e);return t&&(this.clearCache(),this.emit("entryRemoved",{id:e})),t}addRegistry(e){this.config.registries.push(e),this.clearCache();const{authToken:t,...r}=e;this.emit("registryAdded",{config:r})}setRemoteLookup(e){this.config.remoteLookup=e,this.clearCache(),this.emit("remoteLookupChanged",{enabled:e})}clearCache(){this.cache.clear(),this.emit("cacheCleared")}checkRequiredEnvVars(e){const t=[];for(const r of e.requiredEnvVars??[])process.env[r]||t.push(r);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(){const e=await this.getAllEntries(),t=await this.getCategories(),r=await this.getTags();return{totalEntries:e.length,verifiedEntries:e.filter(n=>n.verified).length,categories:t.length,tags:r.length,customEntries:this.customEntries.size}}},ude=new U$}}),dde={};ce(dde,{AgentExposureManager:()=>G$,exposeAgentAsTool:()=>B$,exposeAgentsAsTools:()=>$ur,exposeWorkflowAsTool:()=>z$,exposeWorkflowsAsTools:()=>Uur,globalAgentExposureManager:()=>pde});function B$(e,t={}){const{prefix:r="agent",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:i=y=>y.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:s=!0,executionTimeout:a=3e5,enableLogging:l=!0}=t,c=i(e.name),u=r?`${r}_${c}`:c;let d=e.description;if(o&&e.metadata){const y=[];e.metadata.version&&y.push(`v${e.metadata.version}`),e.metadata.category&&y.push(`category: ${e.metadata.category}`),e.metadata.estimatedDuration&&y.push(`~${e.metadata.estimatedDuration}ms`),y.length>0&&(d+=` [${y.join(", ")}]`)}const p={...n,complexity:n.complexity??"complex",estimatedDuration:e.metadata?.estimatedDuration??n.estimatedDuration,costHint:e.metadata?.costHint??n.costHint,tags:[...n.tags??[],"agent",...e.metadata?.tags??[]]},m=e.inputSchema??{type:"object",properties:{}},f=async(y,v)=>{const w=Date.now();l&&h.debug(`[AgentExposure] Executing agent '${e.id}' as tool '${u}'`);try{const b=v?.config&&typeof v.config=="object"?v.config:{},E=s?{...v,config:{...b,sourceType:"mcp-exposed-agent",agentId:e.id,toolName:u}}:v??{},k=await Et(e.execute(y,E),a),x=Date.now()-w;return l&&h.debug(`[AgentExposure] Agent '${e.id}' completed in ${x}ms`),{success:!0,data:k,metadata:{agentId:e.id,toolName:u,executionTime:x,sourceType:"agent"}}}catch(b){const E=Date.now()-w,k=b instanceof Error?b:ve.toolExecutionFailed(u,new Error(String(b)));return l&&h.error(`[AgentExposure] Agent '${e.id}' failed after ${E}ms: ${k.message}`),{success:!1,error:k.message,metadata:{agentId:e.id,toolName:u,executionTime:E,sourceType:"agent"}}}};return{tool:{name:u,description:d,inputSchema:m,outputSchema:e.outputSchema,annotations:p,execute:f,metadata:{sourceType:"agent",sourceId:e.id,originalName:e.name,...e.metadata}},sourceType:"agent",sourceId:e.id,toolName:u}}function z$(e,t={}){const{prefix:r="workflow",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:i=y=>y.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:s=!0,executionTimeout:a=6e5,enableLogging:l=!0}=t,c=i(e.name),u=r?`${r}_${c}`:c;let d=e.description;if(o){const y=[];e.metadata?.version&&y.push(`v${e.metadata.version}`),e.steps?.length&&y.push(`${e.steps.length} steps`),e.metadata?.estimatedDuration&&y.push(`~${e.metadata.estimatedDuration}ms`),y.length>0&&(d+=` [${y.join(", ")}]`)}const p={...n,complexity:n.complexity??"complex",estimatedDuration:e.metadata?.estimatedDuration??n.estimatedDuration,idempotentHint:e.metadata?.idempotent??n.idempotentHint,tags:[...n.tags??[],"workflow",...e.metadata?.tags??[]]},m=e.inputSchema??{type:"object",properties:{}},f=async(y,v)=>{const w=Date.now();l&&h.debug(`[WorkflowExposure] Executing workflow '${e.id}' as tool '${u}'`);try{const b=v?.config&&typeof v.config=="object"?v.config:{},E=s?{...v,config:{...b,sourceType:"mcp-exposed-workflow",workflowId:e.id,toolName:u}}:v??{},k=await Et(e.execute(y,E),a),x=Date.now()-w;return l&&h.debug(`[WorkflowExposure] Workflow '${e.id}' completed in ${x}ms`),{success:!0,data:k,metadata:{workflowId:e.id,toolName:u,executionTime:x,sourceType:"workflow",stepsCount:e.steps?.length}}}catch(b){const E=Date.now()-w,k=b instanceof Error?b:ve.toolExecutionFailed(u,new Error(String(b)));return l&&h.error(`[WorkflowExposure] Workflow '${e.id}' failed after ${E}ms: ${k.message}`),{success:!1,error:k.message,metadata:{workflowId:e.id,toolName:u,executionTime:E,sourceType:"workflow"}}}};return{tool:{name:u,description:d,inputSchema:m,outputSchema:e.outputSchema,annotations:p,execute:f,metadata:{sourceType:"workflow",sourceId:e.id,originalName:e.name,steps:e.steps,...e.metadata}},sourceType:"workflow",sourceId:e.id,toolName:u}}function $ur(e,t={}){return e.map(r=>B$(r,t))}function Uur(e,t={}){return e.map(r=>z$(r,t))}var G$,pde,mde=S({"src/lib/mcp/agentExposure.ts"(){"use strict";z(),zr(),et(),G$=class{exposedTools=new Map;options;constructor(e={}){this.options=e}exposeAgent(e){const t=B$(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}exposeWorkflow(e){const t=z$(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(){const 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)}}},pde=new G$}}),Bur={};ce(Bur,{ToolIntegrationManager:()=>V$,confirmationMiddleware:()=>gde,createElicitationContext:()=>q$,createRetryMiddleware:()=>qur,createTimeoutMiddleware:()=>Gur,createToolMiddlewareChain:()=>hde,globalToolIntegrationManager:()=>vde,loggingMiddleware:()=>fde,validationMiddleware:()=>yde,wrapToolWithElicitation:()=>j$,wrapToolsWithElicitation:()=>zur});function q$(e,t,r){return{confirm:async(n,o)=>r.confirm(n,{toolName:e,serverId:t,confirmLabel:o?.confirmLabel,cancelLabel:o?.cancelLabel}),getText:async(n,o)=>r.getText(n,{toolName:e,placeholder:o?.placeholder,defaultValue:o?.defaultValue}),select:async(n,o)=>r.select(n,o,{toolName:e}),multiSelect:async(n,o)=>r.multiSelect(n,o,{toolName:e}),form:async(n,o)=>r.form(n,o,{toolName:e,serverId:t}),request:async n=>r.request({...n,toolName:e,serverId:t})}}function j$(e,t={}){const{elicitationManager:r,autoConfirmDestructive:n=!1,elicitationTimeout:o=6e4,enableLogging:i=!0}=t,s=r??new OT({defaultTimeout:o});return{...e,execute:async(a,l)=>{const u=l?.config?.serverId,d=q$(e.name,u,s);if((e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)&&!n&&(i&&h.debug(`[ToolIntegration] Tool '${e.name}' requires confirmation`),!await d.confirm(`This operation (${e.name}) ${e.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:e.name,cancelled:!0}};const m={...l,elicitation:d,toolMeta:{name:e.name,serverId:u,annotations:e.annotations}};return e.execute(a,m)}}}function zur(e,t={}){return e.map(r=>j$(r,t))}function hde(e){return async(t,r,n,o)=>{const i=async s=>{if(s>=e.length)return o();const a=e[s];return a(t,r,n,()=>i(s+1))};return i(0)}}function Gur(e){return async(t,r,n,o)=>Be(o(),e,ve.toolTimeout(t.name,e))}function qur(e,t=1e3){return async(r,n,o,i)=>{if(!(r.annotations?.idempotentHint||r.annotations?.readOnlyHint))return i();const a=Math.max(0,e);let l;for(let c=0;c<=a;c++)try{return await i()}catch(u){l=u instanceof Error?u:ve.toolExecutionFailed(r.name,new Error(String(u))),c<a&&(h.warn(`[ToolMiddleware] Tool '${r.name}' failed, retrying (${c+1}/${a})`),await new Promise(d=>setTimeout(d,t*(c+1))))}throw l??ve.toolExecutionFailed(r.name,new Error("Retry middleware exhausted without captured error"))}}var fde,gde,yde,V$,vde,jur=S({"src/lib/mcp/toolIntegration.ts"(){"use strict";sde(),et(),z(),fde=async(e,t,r,n)=>{const o=Date.now();h.debug(`[ToolMiddleware] Executing tool '${e.name}'`);try{const i=await n(),s=Date.now()-o;return h.debug(`[ToolMiddleware] Tool '${e.name}' completed in ${s}ms`),i}catch(i){const s=Date.now()-o;throw h.error(`[ToolMiddleware] Tool '${e.name}' failed after ${s}ms:`,i),i}},gde=async(e,t,r,n)=>r.elicitation?.confirm&&(e.annotations?.destructiveHint||e.annotations?.requiresConfirmation)&&!await r.elicitation.confirm(`Confirm execution of ${e.name}?`)?{success:!1,error:"Operation cancelled by user",metadata:{cancelled:!0}}:n(),yde=async(e,t,r,n)=>{if(!e.inputSchema)return n();const o=e.inputSchema,i=o.required??[],s=o.properties??{},a=t??{},l=[];for(const c of i)a[c]===void 0&&l.push(c);if(l.length>0){const c=l.map(d=>{const p=s[d];return{name:d,label:d,type:p?.type??"text",required:!0,description:p?.description}}),u=await r.elicitation.form(`Missing required parameters for ${e.name}`,c);if(!u)return{success:!1,error:`Missing required parameters: ${l.join(", ")}`,metadata:{missingParams:l}};Object.assign(a,u)}return n()},V$=class{elicitationManager;middlewares=[];wrappedTools=new Map;constructor(e){this.elicitationManager=e??new OT}setElicitationHandler(e){this.elicitationManager.setHandler(e)}use(e){return this.middlewares.push(e),this}registerTool(e){const t=j$(e,{elicitationManager:this.elicitationManager});return this.wrappedTools.set(e.name,t),t}async executeTool(e,t,r){const n=this.wrappedTools.get(e);if(!n)throw ve.toolNotFound(e,Array.from(this.wrappedTools.keys()));const o=t&&typeof t=="object"?t:{},s=r?.config?.serverId,a=q$(e,s,this.elicitationManager),l={...r,elicitation:a,toolMeta:{name:e,serverId:s,annotations:n.annotations}};return this.middlewares.length===0?n.execute(o,l):hde(this.middlewares)(n,o,l,()=>n.execute(o,l))}getTool(e){return this.wrappedTools.get(e)}getAllTools(){return Array.from(this.wrappedTools.values())}getElicitationManager(){return this.elicitationManager}},vde=new V$}}),wde={};ce(wde,{TOOL_COMPATIBILITY:()=>Ede,batchConvertToMCP:()=>Wur,batchConvertToNeuroLink:()=>Kur,createToolFromFunction:()=>Jur,mcpProtocolToolToServerTool:()=>Vur,mcpToolToNeuroLink:()=>Tde,neuroLinkToolToMCP:()=>bde,sanitizeToolName:()=>_de,serverToolToMCPProtocol:()=>Hur,validateToolName:()=>Xur});function bde(e,t={}){const{inferAnnotations:r=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:i}=t,s=i?`${i}_${e.name}`:e.name,a=r?Ap({name:e.name,description:e.description}):{},l={...n,...a};e.tags?.length&&(l.tags=[...new Set([...l.tags??[],...e.tags])]);const c=e.parameters??{type:"object",properties:{}},u=o?{...e.metadata}:{};return e.category&&(u.category=e.category),e.isAsync!==void 0&&(u.isAsync=e.isAsync),{name:s,description:e.description,inputSchema:c,annotations:l,execute:e.execute,metadata:u}}function Tde(e,t={}){const{removeNamespacePrefix:r}=t;let n=e.name;return r&&e.name.startsWith(`${r}_`)&&(n=e.name.slice(r.length+1)),{name:n,description:e.description,parameters:e.inputSchema,execute:e.execute,category:e.metadata?.category,tags:e.annotations?.tags,metadata:e.metadata}}function Vur(e,t,r={}){const{inferAnnotations:n=!0,defaultAnnotations:o={}}=r,i=e.annotations??{},s=n?Ap({name:e.name,description:e.description??""}):{},a={...o,...s,title:i.title??s.title??o.title,readOnlyHint:i.readOnlyHint??s.readOnlyHint??o.readOnlyHint,destructiveHint:i.destructiveHint??s.destructiveHint??o.destructiveHint,idempotentHint:i.idempotentHint??s.idempotentHint??o.idempotentHint,openWorldHint:i.openWorldHint??s.openWorldHint??o.openWorldHint};return{name:e.name,description:e.description??"No description provided",inputSchema:e.inputSchema,annotations:a,execute:t}}function Hur(e){const t={};e.annotations?.title&&(t.title=e.annotations.title),e.annotations?.readOnlyHint!==void 0&&(t.readOnlyHint=e.annotations.readOnlyHint),e.annotations?.destructiveHint!==void 0&&(t.destructiveHint=e.annotations.destructiveHint),e.annotations?.idempotentHint!==void 0&&(t.idempotentHint=e.annotations.idempotentHint),e.annotations?.openWorldHint!==void 0&&(t.openWorldHint=e.annotations.openWorldHint);const r=e.inputSchema??{type:"object",properties:{}};return{name:e.name,description:e.description,inputSchema:{type:"object",properties:r.properties??{},required:"required"in r?r.required:void 0},annotations:Object.keys(t).length>0?t:void 0}}function Wur(e,t={}){return e.map(r=>bde(r,t))}function Kur(e,t={}){return e.map(r=>Tde(r,t))}function Jur(e,t,r,n){const o=Ap({name:e,description:t});return{name:e,description:t,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(i,s)=>await Et(r(i,s),3e4,`Tool '${e}' execution timed out after 30000ms`),metadata:n?.metadata}}function Xur(e){const t=[];return!e||typeof e!="string"?t.push("Tool name is required and must be a string"):(e.length>64&&t.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e)||t.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:t.length===0,errors:t}}function _de(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(t)||(t=`_${t}`),t.length>64&&(t=t.slice(0,64)),t}var Ede,H$=S({"src/lib/mcp/toolConverter.ts"(){"use strict";WA(),zr(),Ede={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}}}}),DT,d0,Yur,uvn=S({async"src/lib/core/redisConversationMemoryManager.ts"(){"use strict";Vt(),Zt(),Bt(),qx(),hy(),DYt(),wVt(),await bu(),lt(),et(),gb(),z(),xVt(),yN(),S3(),DT=$e.redis,d0=5e3,Yur=class{config;isInitialized=!1;summarizationEngine=new qre;redisConfig;redisClient=null;pendingToolExecutions=new Map;titleGenerationInProgress=new Set;summarizationInProgress=new Set;constructor(e,t={}){this.config=e,this.redisConfig=Mie(t)}async initialize(){if(this.isInitialized){h.debug("[RedisConversationMemoryManager] Already initialized, skipping");return}await DT.startActiveSpan("memory.initialize",{kind:ln.CLIENT,attributes:{"redis.host":this.redisConfig.host,"redis.port":this.redisConfig.port,"redis.key_prefix":this.redisConfig.keyPrefix}},async e=>{try{h.debug("[RedisConversationMemoryManager] Initializing with config",{host:this.redisConfig.host,port:this.redisConfig.port,keyPrefix:this.redisConfig.keyPrefix,ttl:this.redisConfig.ttl}),this.redisClient=await xie(this.redisConfig),this.isInitialized=!0,h.info("RedisConversationMemoryManager initialized",{storage:"redis",host:this.redisConfig.host,port:this.redisConfig.port,maxSessions:this.config.maxSessions,maxTurnsPerSession:this.config.maxTurnsPerSession}),h.debug("[RedisConversationMemoryManager] Redis client created successfully",{clientType:this.redisClient?.constructor?.name||"unknown",isConnected:!!this.redisClient})}catch(t){throw e.setStatus({code:ze.ERROR,message:t instanceof Error?t.message:String(t)}),e.recordException(t instanceof Error?t:new Error(String(t))),h.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 dl("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,r){if(await this.ensureInitialized(),!this.redisClient)return;const n=this.redisClient;return DT.startActiveSpan("memory.getSession",{kind:ln.CLIENT,attributes:{"session.id":e}},async o=>{t&&o.setAttribute("user.id",t);try{const i=fa(this.redisConfig,e,t),s=await Be(n.get(i),d0),a=await this.hydrateMessages(Ha(s||null),i);if(!a){o.setAttribute("session.found",!1);return}o.setAttribute("session.found",!0);const l=s?Buffer.byteLength(s,"utf8"):0,c=a.messages.length,u=!!a.summarizedUpToMessageId,d=u?a.messages.findIndex(m=>m.id===a.summarizedUpToMessageId):-1,p=u&&d!==-1?c-d-1:c;return o.setAttribute("message.count",c),o.setAttribute("blob.size_bytes",l),h.info("[ConversationMemory] Session loaded",{requestId:r,sessionId:e,blobSizeBytes:l,messageCount:c,hasSummary:u,recentMessageCount:p}),l>512*1024&&h.warn("[ConversationMemory] Large session blob",{requestId:r,sessionId:e,blobSizeBytes:l,messageCount:c}),{sessionId:a.sessionId,userId:a.userId,messages:a.messages,summarizedUpToMessageId:a.summarizedUpToMessageId,summarizedMessage:a.summarizedMessage,tokenThreshold:a.tokenThreshold,lastTokenCount:a.lastTokenCount,lastCountedAt:a.lastCountedAt,lastApiTokenCount:a.lastApiTokenCount,createdAt:new Date(a.createdAt).getTime(),lastActivity:new Date(a.updatedAt).getTime()}}catch(i){o.setStatus({code:ze.ERROR,message:i instanceof Error?i.message:String(i)}),o.recordException(i instanceof Error?i:new Error(String(i))),h.error("[RedisConversationMemoryManager] Failed to get session",{sessionId:e,userId:t,error:i instanceof Error?i.message:String(i)});return}finally{o.end()}})}async getSessionRaw(e,t){try{if(await this.ensureInitialized(),!this.redisClient)return null;const r=fa(this.redisConfig,e,t),n=await this.redisClient.get(r);return this.hydrateMessages(Ha(n||null),r)}catch(r){return h.error("[RedisConversationMemoryManager] Failed to get raw session",{sessionId:e,userId:t,error:r instanceof Error?r.message:String(r)}),null}}async getUserSessions(e){if(await this.ensureInitialized(),!this.redisClient)return h.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];try{const t=Cie(this.redisConfig,e),r=await this.redisClient.sMembers(t);return Array.from(r).map(String)}catch(t){return h.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{const r=Cie(this.redisConfig,e);await qln(this.redisClient,r,t,this.redisConfig.ttl)}catch(r){h.error("[RedisConversationMemoryManager] Failed to add session to user set",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r)})}}async removeUserSession(e,t){if(!this.redisClient||!e)return!1;try{const r=Cie(this.redisConfig,e),n=await this.redisClient.sRem(r,t);return Number(n)>0}catch(r){return h.error("[RedisConversationMemoryManager] Failed to remove session from user set",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r)}),!1}}generateTimestamp(){return new Date().toISOString()}async storeToolExecution(e,t,r,n,o){h.debug("[RedisConversationMemoryManager] Storing tool execution temporarily",{sessionId:e,userId:t,toolCallsCount:r?.length||0,toolResultsCount:n?.length||0});try{const i=t||"randomUser",s=`${e}:${i}`,a={toolCalls:(r||[]).map(c=>({...c,timestamp:o})),toolResults:(n||[]).map(c=>({...c,timestamp:o})),timestamp:Date.now()},l=this.pendingToolExecutions.get(s);l&&(h.debug("[RedisConversationMemoryManager] Merging with existing pending tool data",{sessionId:e,existingToolCalls:l.toolCalls.length,existingToolResults:l.toolResults.length,newToolCalls:r?.length||0,newToolResults:n?.length||0}),a.toolCalls=[...l.toolCalls,...a.toolCalls],a.toolResults=[...l.toolResults,...a.toolResults]),this.pendingToolExecutions.set(s,a),h.debug("[RedisConversationMemoryManager] Tool execution stored temporarily",{sessionId:e,userId:i,pendingKey:s,totalToolCalls:a.toolCalls.length,totalToolResults:a.toolResults.length}),this.cleanupStalePendingData()}catch(i){h.error("[RedisConversationMemoryManager] Failed to store tool execution temporarily",{sessionId:e,error:i instanceof Error?i.message:String(i)})}}async storeConversationTurn(e){return h.debug("[RedisConversationMemoryManager] Storing conversation turn",{sessionId:e.sessionId,userId:e.userId}),await this.ensureInitialized(),DT.startActiveSpan("memory.storeTurn",{kind:ln.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");const r=fa(this.redisConfig,e.sessionId,e.userId),n=await this.redisClient.get(r);let o=await this.hydrateMessages(Ha(n),r);if(SVt(o?.messages??[],e.turnId))return;const i=y1(o),s=o?.messages.length??0,a=new Date().toISOString(),l=e.userId||"randomUser";if(o)o.updatedAt=a;else{const f=`${e.sessionId}:${l}`,g=gt.bind(gt.active(),async()=>{if(!this.titleGenerationInProgress.has(f)){this.titleGenerationInProgress.add(f);try{const y=await this.generateConversationTitle(e.userMessage),v=fa(this.redisConfig,e.sessionId,e.userId||void 0),w=await this.redisClient?.get(v),b=Ha(w||null);if(b){b.title=y,b.updatedAt=new Date().toISOString();const E=Iie(b);this.redisClient&&await Rie(this.redisClient,v,E,this.redisConfig.ttl)}}catch(y){h.warn("[RedisConversationMemoryManager] Failed to generate conversation title in background",{sessionId:e.sessionId,userId:l,error:y instanceof Error?y.message:String(y)})}finally{this.titleGenerationInProgress.delete(f)}}});setImmediate(g),o={id:it(),title:"New Conversation",sessionId:e.sessionId,userId:l,createdAt:e.startTimeStamp?.toISOString()||a,updatedAt:e.startTimeStamp?.toISOString()||a,messages:[]}}const c=e.providerDetails?eVt(e.providerDetails.provider,e.providerDetails.model,this.config.tokenThreshold,o.tokenThreshold):this.config.tokenThreshold||5e4,u={...EVt(TVt(e)),timestamp:e.startTimeStamp?.toISOString()||this.generateTimestamp(),role:"user",content:e.userMessage};o.messages.push(u),await this.flushPendingToolData(o,e.sessionId,l),e.skillMessages&&e.skillMessages.length>0&&o.messages.push(...e.skillMessages);const d={...EVt(_Vt(e,e.thoughtSignature)),timestamp:this.generateTimestamp(),role:"assistant",content:e.aiResponse,events:e.events||void 0};o.messages.push(d),e.tokenUsage&&(o.lastApiTokenCount=e.tokenUsage),h.info("[RedisConversationMemoryManager] Added new messages",{sessionId:o.sessionId,userId:o.userId});const p=e.enableSummarization!==void 0?e.enableSummarization:this.config.enableSummarization;if(await this.persistConversation(o,e.sessionId,e.userId,i?s:void 0),p){const f=e.userId||"randomUser",g=`${e.sessionId}:${f}`;if(this.summarizationInProgress.has(g))h.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:e.sessionId,userId:f});else{const y=gt.bind(gt.active(),async()=>{try{await this.checkAndSummarize(o,c,e.sessionId,e.userId,e.requestId)}catch(v){h.error("Background summarization failed",{sessionId:o.sessionId,error:v instanceof Error?v.message:String(v)})}});setImmediate(y)}}const m=Buffer.byteLength(_3(o),"utf8");h.info("[ConversationMemory] Turn stored",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:m,totalMessages:o.messages.length,userMsgChars:e.userMessage.length,assistantMsgChars:e.aiResponse.length}),m>512*1024&&h.warn("[ConversationMemory] Large session blob",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:m,messageCount:o.messages.length}),this.redisConfig.ttl>0&&await this.redisClient.expire(r,this.redisConfig.ttl),e.userId&&await this.addUserSession(e.userId,e.sessionId),t.setAttribute("message.count",o.messages.length),t.setStatus({code:ze.OK}),h.debug("[RedisConversationMemoryManager] Successfully stored conversation turn",{sessionId:e.sessionId,totalMessages:o.messages.length,title:o.title})}catch(r){throw t.setStatus({code:ze.ERROR,message:r instanceof Error?r.message:String(r)}),t.recordException(r instanceof Error?r:new Error(String(r))),new dl(`Failed to store conversation turn in Redis for session ${e.sessionId}`,"STORAGE_ERROR",{sessionId:e.sessionId,error:r instanceof Error?r.message:String(r)})}finally{t.end()}})}async checkAndSummarize(e,t,r,n,o){const i=n||"randomUser",s=`${r}:${i}`;if(this.summarizationInProgress.has(s)){h.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:r,userId:i});return}this.summarizationInProgress.add(s);try{const a={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()},l=await this.summarizationEngine.checkAndSummarize(a,t,this.config,"[RedisConversationMemoryManager]",o);if(e.lastTokenCount=a.lastTokenCount,e.lastCountedAt=a.lastCountedAt,l&&(e.summarizedUpToMessageId=a.summarizedUpToMessageId,e.summarizedMessage=a.summarizedMessage,this.redisClient)){const c=fa(this.redisConfig,r,n),u=await this.redisClient.get(c);if(u){const d=Ha(u);if(d){d.summarizedUpToMessageId=e.summarizedUpToMessageId,d.summarizedMessage=e.summarizedMessage,d.lastTokenCount=e.lastTokenCount,d.lastCountedAt=e.lastCountedAt;const p=y1(d)?_3(d):Iie(d);await Rie(this.redisClient,c,p,this.redisConfig.ttl)}}}}catch(a){h.error("Token counting or summarization failed",{sessionId:e.sessionId,error:a instanceof Error?a.message:String(a)})}finally{this.summarizationInProgress.delete(s)}}isConversationBlobKey(e){return!Vln(e)&&!e.endsWith(":sessions")&&!e.startsWith(this.redisConfig.userSessionsKeyPrefix)}async hydrateMessages(e,t){if(!e||!y1(e)||!this.redisClient)return e;const r=await Be(this.redisClient.lRange(`${t}${Fb}`,0,-1),d0);return e.messages=Hln(r.map(n=>n.toString())),e}async countMessages(e,t){return!y1(e)||!this.redisClient?e.messages.length:Number(await Be(this.redisClient.lLen(`${t}${Fb}`),d0))}async loadConversation(e,t){if(!this.redisClient)return null;const r=fa(this.redisConfig,e,t);return this.hydrateMessages(Ha(await this.redisClient.get(r)),r)}async persistConversation(e,t,r,n){if(!this.redisClient)return;const o=fa(this.redisConfig,t,r),i=jln(this.redisConfig,t,r),s=this.redisClient.multi();n===void 0&&s.del(i);const a=n===void 0?e.messages:e.messages.slice(n);a.length>0&&s.rPush(i,Wln(a)),s.set(o,_3(e)),this.redisConfig.ttl>0&&(s.expire(o,this.redisConfig.ttl),s.expire(i,this.redisConfig.ttl)),await Be(s.exec(),d0)}async buildContextMessages(e,t,r,n){if(h.debug("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,enableSummarization:r}),await this.ensureInitialized(),!this.redisClient)return h.warn("[RedisConversationMemoryManager] Redis client not available in buildContextMessages"),[];const o=this.redisClient;return DT.startActiveSpan("memory.buildContext",{kind:ln.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async i=>{try{h.info("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,method:"buildContextMessages"});const s=fa(this.redisConfig,e,t),a=await Be(o.get(s),d0),l=await this.hydrateMessages(Ha(a||null),s);if(h.debug("[RedisConversationMemoryManager] Retrieved conversation for context building",{sessionId:e,userId:t,conversationFound:!!l}),!l)return i.setAttribute("session.found",!1),i.setStatus({code:ze.OK}),[];const c={sessionId:l.sessionId,userId:l.userId,messages:l.messages,summarizedUpToMessageId:l.summarizedUpToMessageId,summarizedMessage:l.summarizedMessage,tokenThreshold:l.tokenThreshold,lastTokenCount:l.lastTokenCount,lastCountedAt:l.lastCountedAt,createdAt:new Date(l.createdAt).getTime(),lastActivity:new Date(l.updatedAt).getTime()},u=Mre(c,n);h.debug("[RedisConversationMemoryManager] Built context messages from pointer",{sessionId:e,userId:t,contextMessageCount:u.length,pointerMessageId:c.summarizedUpToMessageId||"none"});const d=this.config?.contextCompaction?.sendToolPreview===!0,p=u.map(m=>{if(m.role!=="tool_result")return m;const f=d&&m.metadata?.toolOutputPreview?m.metadata.toolOutputPreview:m.content;let g=m.result;if(m.result&&m.result.result===void 0){let y=f;try{y=JSON.parse(f)}catch{}g={...m.result,result:y}}return h.debug("[RedisConversationMemoryManager] Processing tool_result message for context",{sessionId:e,userId:t,messageId:m.id,sendToolPreview:d,hasPreview:!!m.metadata?.toolOutputPreview,contentLength:f?String(f).length:0,resultHydrated:g!==m.result}),{...m,content:f,result:g}});return i.setAttribute("context.message_count",p.length),i.setStatus({code:ze.OK}),h.info("[RedisConversationMemoryManager] Retrieved context messages",{sessionId:e,userId:t}),p}catch(s){throw i.setStatus({code:ze.ERROR,message:s instanceof Error?s.message:String(s)}),i.recordException(s instanceof Error?s:new Error(String(s))),s}finally{i.end()}})}async getUserSessionMetadata(e,t){if(h.debug("[RedisConversationMemoryManager] Getting user session metadata",{userId:e,sessionId:t}),await this.ensureInitialized(),!this.redisClient)return h.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e,sessionId:t}),null;try{const r=fa(this.redisConfig,t,e),n=await this.redisClient.get(r);if(!n)return h.debug("[RedisConversationMemoryManager] No session data found",{userId:e,sessionId:t,sessionKey:r}),null;const o=Ha(n);return o?{id:o.sessionId,title:o.title,createdAt:o.createdAt,updatedAt:o.updatedAt,metadata:o.additionalMetadata?.agenticLoopReports?{agenticLoopReports:o.additionalMetadata.agenticLoopReports}:void 0}:(h.debug("[RedisConversationMemoryManager] No valid conversation data found",{userId:e,sessionId:t,sessionKey:r}),null)}catch(r){return h.error("[RedisConversationMemoryManager] Failed to get user session metadata",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}),null}}async getUserSessionHistory(e,t){h.debug("[RedisConversationMemoryManager] Getting user session history via getUserSessionObject",{userId:e,sessionId:t});try{const r=await this.getUserSessionObject(e,t);return r?r.messages:(h.debug("[RedisConversationMemoryManager] No session object found, returning null",{userId:e,sessionId:t}),null)}catch(r){return h.error("[RedisConversationMemoryManager] Failed to get user session history via getUserSessionObject",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"UnknownError",stack:r instanceof Error?r.stack:void 0}),null}}async getUserSessionObject(e,t){if(h.debug("[RedisConversationMemoryManager] Getting complete user session object",{userId:e,sessionId:t,method:"getUserSessionObject"}),!e||typeof e!="string")return h.warn("[RedisConversationMemoryManager] Invalid userId provided",{userId:e,sessionId:t}),null;if(!t||typeof t!="string")return h.warn("[RedisConversationMemoryManager] Invalid sessionId provided",{userId:e,sessionId:t}),null;if(await this.ensureInitialized(),!this.redisClient)return h.warn("[RedisConversationMemoryManager] Redis client not available for getUserSessionObject",{userId:e,sessionId:t}),null;try{const r=fa(this.redisConfig,t,e),n=await this.redisClient.get(r);if(!n)return h.debug("[RedisConversationMemoryManager] No conversation data found in Redis",{userId:e,sessionId:t,sessionKey:r}),null;const o=await this.hydrateMessages(Ha(n),r);return o?!o.messages||!Array.isArray(o.messages)?(h.warn("[RedisConversationMemoryManager] Invalid conversation structure - missing messages array",{userId:e,sessionId:t,hasMessages:!!o.messages,messagesType:typeof o.messages}),null):o:(h.debug("[RedisConversationMemoryManager] Failed to deserialize conversation data",{userId:e,sessionId:t,sessionKey:r,dataLength:n.length}),null)}catch(r){return h.error("[RedisConversationMemoryManager] Failed to get complete user session object",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"UnknownError",stack:r instanceof Error?r.stack:void 0}),null}}async generateConversationTitle(e){h.info("[RedisConversationMemoryManager] Generating conversation title",{userMessageLength:e.length,userMessagePreview:e.substring(0,100)});try{const t=new GT({conversationMemory:{enabled:!1}}),r=`Generate a clear, concise, and descriptive title (20-25 letters maximum) for a conversation based on the following user message.
1894
+ \u26A0\uFE0F CRITICAL: Content MUST fit within slide box. Keep text SHORT.`,ccr=5,ucr=50,dcr=10,pcr=5e3,mcr=Object.keys(LC),hcr=["business","students","technical","general"],fcr=["professional","casual","educational","persuasive"],gcr=["16:9","4:3"],M$={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}},que=6e4,P$=3e4,jue=5,xc=3e5}}),gu,Ll,Vue=S({"src/lib/features/ppt/pptError.ts"(){"use strict";et(),gu={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"},Ll=class extends Me{constructor(e,t,r,n){super({code:t,message:e,category:"execution",severity:"high",retriable:!1,context:{...r,originalMessage:n?.message},originalError:n}),this.name="PPTError"}}}}),ycr={};ce(ycr,{PPT_VALID_PROVIDERS:()=>_T,bufferToDataUrl:()=>FC,calculateFontSize:()=>kcr,createFormattedTextProps:()=>TT,ensureOutputDirectory:()=>wcr,extractPPTContext:()=>l0n,generateOutputPath:()=>vcr,getEffectivePPTProvider:()=>c0n,getFailureStage:()=>Hue,getLayoutName:()=>Ecr,hasMarkdownFormatting:()=>bT,isLogoConfig:()=>Tcr,isObject:()=>bcr,normalizeLogoConfig:()=>_cr,parseMarkdownText:()=>wT,toError:()=>Scr,validateImageBuffer:()=>Wue});function l0n(e){const t=e.output?.ppt;if(!t)throw new Ll("PPT options are required when mode is 'ppt'",gu.INVALID_INPUT,{field:"output.ppt"});let r;if(t.logoPath){if(Buffer.isBuffer(t.logoPath)||typeof t.logoPath=="string")r=t.logoPath;else if(typeof t.logoPath=="object"&&"data"in t.logoPath){const o=t.logoPath.data;r=Buffer.isBuffer(o)||typeof o=="string"?o:void 0}}const n=[];if(e.input?.images){for(const o of e.input.images)if(Buffer.isBuffer(o)||typeof o=="string")n.push(o);else if(typeof o=="object"&&"data"in o){const i=o.data;(Buffer.isBuffer(i)||typeof i=="string")&&n.push(i)}}return!r&&n.length>0&&(r=n[0]),{topic:e.input?.text||"",pages:t.pages,theme:t.theme??"AI will decide",audience:t.audience??"AI will decide",tone:t.tone??"AI will decide",generateAIImages:t.generateAIImages??!1,aspectRatio:t.aspectRatio||"16:9",outputPath:t.outputPath,logo:r,images:n.length>0?n:void 0,provider:e.provider,model:e.model}}async function c0n(e,t,r,n){const{ErrorFactory:o}=await Promise.resolve().then(()=>(et(),AS)),i=t.toLowerCase();if(_T.includes(i)){const s=e,a=r||s?.modelName||s?.getDefaultModel?.()||"";return h.debug("[PPT Utils] Current provider is valid for PPT",{provider:t,model:a}),{provider:e,providerName:t,modelName:a,wasAutoSelected:!1}}h.info("[PPT Utils] Current provider not valid for PPT, auto-selecting",{currentProvider:t});for(const s of _T)if(qce(s)){h.info("[PPT Utils] Auto-selected PPT provider",{originalProvider:t,selectedProvider:s});const{AIProviderFactory:a}=await Promise.resolve().then(()=>(Qa(),xI)),{withTimeout:l}=await Promise.resolve().then(()=>(et(),AS)),{PPT_GENERATION_TIMEOUT_MS:c}=await Promise.resolve().then(()=>(vT(),Uue)),u=await l(a.createProvider(s,void 0,!0,n),c/4,o.toolTimeout("createProvider",c/4));return{provider:u,providerName:s,modelName:u.modelName,wasAutoSelected:!0}}throw o.invalidParameters("ppt-generation",new Error(`No PPT-compatible provider available. Configure one of: ${_T.join(", ")}`),{currentProvider:t,validProviders:_T})}function vcr(e){const t=new Date().toISOString().replace(/[:.]/g,"-").substring(0,19),n=`${e.topic.substring(0,30).replace(/[^a-zA-Z0-9]/g,"_").toLowerCase()}_${t}.pptx`;return e.outputPath?e.outputPath.endsWith(".pptx")?e.outputPath:Mt(e.outputPath,n):Mt(process.cwd(),"output",n)}async function wcr(e){const t=I7(e);try{const{withTimeout:r,ErrorFactory:n}=await Promise.resolve().then(()=>(et(),AS)),{PPT_GENERATION_TIMEOUT_MS:o}=await Promise.resolve().then(()=>(vT(),Uue));await r(rZ(t,{recursive:!0}),o/8,n.toolTimeout("mkdirOutputDirectory",o/8))}catch(r){const n=r instanceof Error?r:new Error(String(r));throw new Ll(`Failed to create output directory: ${t}`,gu.FILE_WRITE_FAILED,{directory:t},n)}}function bcr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Tcr(e){return bcr(e)?"data"in e&&(Buffer.isBuffer(e.data)||typeof e.data=="string"):!1}function _cr(e){return e===null?null:Buffer.isBuffer(e)||typeof e=="string"?{data:e,position:"bottom-right",width:1,height:.4,showOn:"all-slides"}:Tcr(e)?e:null}function Ecr(e){switch(e){case"16:9":return"LAYOUT_16x9";case"4:3":return"LAYOUT_4x3";default:return"LAYOUT_16x9"}}function Scr(e){return e instanceof Error?e:new Error(String(e))}function Hue(e){return e.contentPlan===null?"content-planning":e.slides===null?"slide-generation":e.outputPath===null?"pptx-assembly":"file-output"}function Wue(e){return!e||e.length===0?{isValid:!1,mimeType:"",format:"",error:"Empty or undefined buffer"}:e.length<100?{isValid:!1,mimeType:"",format:"",error:`Buffer too small (${e.length} bytes)`}:e[0]===255&&e[1]===216&&e[2]===255?{isValid:!0,mimeType:"image/jpeg",format:"JPEG"}:e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?{isValid:!0,mimeType:"image/png",format:"PNG"}:e[0]===71&&e[1]===73&&e[2]===70?{isValid:!0,mimeType:"image/gif",format:"GIF"}:e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e.length>12&&e.slice(8,12).toString()==="WEBP"?{isValid:!0,mimeType:"image/webp",format:"WebP"}:e[0]===66&&e[1]===77?{isValid:!0,mimeType:"image/bmp",format:"BMP"}:{isValid:!1,mimeType:"image/png",format:"unknown",error:`Unknown format (magic bytes: ${e.slice(0,4).toString("hex")})`}}function FC(e){const t=Wue(e);return!t.isValid&&t.format===""?(h.warn("[bufferToDataUrl] Invalid image buffer",{error:t.error}),null):`data:${t.mimeType||"image/png"};base64,${e.toString("base64")}`}function wT(e){if(!e||typeof e!="string")return[{text:e||""}];const t=[],r=/(\*\*\*(.+?)\*\*\*|\*\*(.+?)\*\*|\*(.+?)\*)/g;let n=0;for(;;){const o=r.exec(e);if(o===null)break;o.index>n&&t.push({text:e.slice(n,o.index)}),o[2]?t.push({text:o[2],bold:!0,italic:!0}):o[3]?t.push({text:o[3],bold:!0}):o[4]&&t.push({text:o[4],italic:!0}),n=r.lastIndex}return n<e.length&&t.push({text:e.slice(n)}),t.length===0&&t.push({text:e}),t}function bT(e){return!e||typeof e!="string"?!1:/\*{1,3}[^*]+\*{1,3}/.test(e)}function TT(e,t){return e.map(r=>({text:r.text,options:{fontSize:t.fontSize,fontFace:t.fontFace,color:t.color,bold:r.bold||t.baseBold||!1,italic:r.italic||!1}}))}function kcr(e,t=18){return e<=5?t:e<=7?Math.max(12,t-2):e<=10?Math.max(12,t-4):12}var _T,Kue=S({"src/lib/features/ppt/utils.ts"(){"use strict";yi(),Tr(),Gh(),z(),Vue(),_T=["vertex","openai","azure","anthropic","google-ai","bedrock"]}});function u0n(e,t,r=!1){const n=t/72,o=.42,i=r?1.1:1,s=n*o*i;return e.length*s}function Os(e,t,r,n=!0){if(e.addText(t,{x:Gt.title.x,y:Gt.title.y,w:Gt.title.w,h:Gt.title.h,fontSize:r.fonts.sizes.heading,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),bold:!0,fit:Ot}),n){const o=u0n(t,r.fonts.sizes.heading,!0),i=Gt.title.w,a=Math.min(i,Math.max(1,o));e.addShape("rect",{x:Gt.title.x,y:Gt.title.y+Gt.title.h+.1,w:a,h:.03,fill:{color:r.colors.primary.replace("#","")}})}}function xcr(e){const{slide:t,bullets:r,startX:n,startY:o,width:i,theme:s,itemSpacing:a=.45}=e;if(!r||r.length===0)return;const l=Math.max(a,ST*2);r.forEach((c,u)=>{if(!c||!c.text)return;const d=c.bold||c.emphasis||!1,p=c.color?.replace("#","")||s.colors.text.replace("#","");if(bT(c.text)){const m=wT(c.text),f=[{text:"\u2022 ",options:{fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p}},...TT(m,{fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p,baseBold:d})];t.addText(f,{x:n,y:o+u*l,w:i,h:Math.max(.4,l-ST),fit:Ot})}else{const m=`\u2022 ${c.text}`;t.addText(m,{x:n,y:o+u*l,w:i,h:Math.max(.4,l-ST),fontSize:s.fonts.sizes.body,fontFace:s.fonts.body,color:p,bold:d,fit:Ot})}})}function Acr(e,t,r,n,o="content",i){if(!t||t.length===0)return;if(i?.useIndividualBullets){xcr({slide:e,bullets:t,startX:r.x,startY:r.y,width:r.w,theme:n,itemSpacing:i.itemSpacing??.45});return}const s=Wlr(o),a=kcr(t.length,s.baseFontSize||n.fonts.sizes.body),l=[];t.forEach(c=>{if(!c||!c.text)return;const u=c.bulletStyle||s.bulletStyle||"disc",d=c.fontSize||a,p=c.color?.replace("#","")||n.colors.text.replace("#",""),m=c.bold??c.emphasis??!1;let f;if(c.icon?f={code:c.icon}:f=Klr(u),bT(c.text)){const g=wT(c.text),y=TT(g,{fontSize:d,fontFace:n.fonts.body,color:p,baseBold:m});l.push({text:y,options:{bullet:f,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}})}else l.push({text:c.text,options:{bullet:f,fontSize:d,fontFace:n.fonts.body,color:p,bold:m,indentLevel:0,paraSpaceBefore:6,paraSpaceAfter:6}});c.subBullets&&c.subBullets.length>0&&c.subBullets.forEach(g=>{if(bT(g)){const y=wT(g),v=TT(y,{fontSize:Math.max(10,d-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#","")});l.push({text:v,options:{bullet:!0,indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})}else l.push({text:g,options:{bullet:!0,fontSize:Math.max(10,d-2),fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),indentLevel:1,paraSpaceBefore:3,paraSpaceAfter:3}})})}),e.addText(l,{x:r.x,y:r.y,w:r.w,h:r.h,valign:"top",fit:Ot})}function Jue(e,t,r){const n=Wue(t);if(!n.isValid&&n.format===""){h.warn("[addImage] Invalid image buffer",{error:n.error});return}n.isValid||h.warn("[addImage] Image validation warning, attempting to add anyway",{error:n.error,mimeType:n.mimeType});const o=FC(t);if(!o){h.warn("[addImage] Failed to convert buffer to data URL");return}try{e.addImage({data:o,x:r.x,y:r.y,w:r.w,h:r.h,sizing:{type:"cover",w:r.w,h:r.h}})}catch(i){h.error("[addImage] Failed to add image to slide",{error:i instanceof Error?i.message:String(i)})}}function d0n(e){switch(e){case"chart-bar":return"bar";case"chart-line":return"line";case"chart-pie":return"pie";case"chart-area":return"area";default:return"bar"}}function p0n(e,t,r,n,o){const i=r.layoutOptions||{},s=i.title||{},a=i.subtitle||{},l=i.background||{},c=o?FC(o):null;if(c)e.background={data:c},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}});else if(l.color||l.useThemePrimary||l.useThemeSecondary){const m=l.useThemePrimary?n.colors.primary:l.useThemeSecondary?n.colors.secondary:l.color||n.colors.background;e.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:m.replace("#","")}})}const u=o||l.color||l.useThemePrimary||l.useThemeSecondary,d=u?"FFFFFF":n.colors.text.replace("#",""),p=u?"FFFFFF":n.colors.muted.replace("#","");e.addText(t,{x:s.x??.5,y:s.y??2,w:s.w??9,h:s.h??1.2,fontSize:s.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:s.color?.replace("#","")??d,align:s.align??"center",bold:!0,fit:Ot}),r.subtitle&&e.addText(r.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("#","")??p,align:a.align??"center",fit:Ot})}function m0n(e,t,r,n){const o=r.layoutOptions||{},i=o.sectionNumber||{},s=o.title||{},a=o.subtitle||{},l=o.background||{};if(l.color&&e.addShape("rect",{x:0,y:0,w:10,h:5.625,fill:{color:l.color.replace("#","")}}),r.sectionNumber){const c=i.style==="watermark",u=i.style==="small";e.addText(String(r.sectionNumber).padStart(2,"0"),{x:i.x??(c?5.5:.5),y:i.y??(c?.5:1.5),w:c?5:2,h:c?4:1,fontSize:i.fontSize??(c?200:u?32:72),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:c?"right":"left",transparency:c?70:0})}e.addText(t,{x:s.x??.5,y:s.y??2.5,w:s.w??9,h:s.h??1,fontSize:s.fontSize??n.fonts.sizes.title,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),bold:!0,align:s.align??"left"}),r.subtitle&&e.addText(r.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 h0n(e,t,r,n,o){if(o){const s=FC(o);s&&(e.background={data:s},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:40}}))}const i=o?"FFFFFF":n.colors.text.replace("#","");if(e.addText(t||"Thank You!",{x:.5,y:1.8,w:9,h:1,fontSize:n.fonts.sizes.title,fontFace:n.fonts.heading,color:i,align:"center",bold:!0,fit:Ot}),r.cta&&e.addText(r.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:Ot}),r.contactInfo){const s=[];if(r.contactInfo.email&&s.push(`Email: ${r.contactInfo.email}`),r.contactInfo.website&&s.push(`Web: ${r.contactInfo.website}`),r.contactInfo.phone&&s.push(`Phone: ${r.contactInfo.phone}`),s.length>0&&e.addText(s.join(" \u2022 "),{x:.5,y:4.2,w:9,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:i,align:"center",fit:Ot}),r.contactInfo.social&&Array.isArray(r.contactInfo.social)&&r.contactInfo.social.length>0){const a=r.contactInfo.social.map(l=>`${l.platform||""}: ${l.handle||""}`).join(" \u2022 ");e.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 Xue(e){const{slide:t,title:r,content:n,layout:o,theme:i,imageBuffer:s,slideType:a="content"}=e;Os(t,r,i);const l=s&&o.includes("image"),c=l?o.includes("left")?Gt.contentRight:Gt.contentLeft:Gt.contentFull;if(n.bullets&&n.bullets.length>0?Acr(t,n.bullets,c,i,a):n.body&&t.addText(n.body,{x:c.x,y:c.y,w:c.w,h:c.h,fontSize:i.fonts.sizes.body,fontFace:i.fonts.body,color:i.colors.text.replace("#",""),valign:"top"}),s&&l){const u=o.includes("left")?Gt.imageLeft:Gt.imageRight;Jue(t,s,u)}}function f0n(e,t,r,n,o,i){if(n==="image-full-overlay"&&i){const s=FC(i);s?(e.background={data:s},e.addShape("rect",{x:0,y:0,w:"100%",h:"100%",fill:{color:"000000",transparency:50}}),e.addText(t,{x:.5,y:4.2,w:9,h:1,fontSize:o.fonts.sizes.heading,fontFace:o.fonts.heading,color:"FFFFFF",bold:!0,fit:Ot})):Os(e,t,o)}else n==="image-centered"||n==="image-full-overlay"?(Os(e,t,o),i?Jue(e,i,Gt.imageCentered):(e.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"}}),e.addText("\u{1F4F7}",{x:1.5,y:2.8,w:7,h:1,fontSize:48,align:"center",valign:"middle",fit:Ot}),e.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:Ot})),r.caption&&e.addText(r.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:Ot})):Xue({slide:e,title:t,content:r,layout:n,theme:o,imageBuffer:i})}function Ccr(e,t,r,n,o){Os(e,t,n,!1);const i={headerY:o?.headerY??1.3,headerHeight:o?.headerHeight??.5,bulletsStartY:o?.bulletsStartY??2,columnGap:o?.columnGap??.3,highlightFirstColumn:o?.highlightFirstColumn??!0},s=r.length;if(s===0)return;const a=9,l=(s-1)*i.columnGap,c=(a-l)/s,u=.5;r.forEach((d,p)=>{if(!d)return;const m=u+p*(c+i.columnGap),f=i.highlightFirstColumn&&p===0;if(d.title){e.addShape("roundRect",{x:m,y:i.headerY,w:c,h:i.headerHeight,fill:{color:f?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05});const g=s<=2?n.fonts.sizes.body:n.fonts.sizes.body-2;e.addText(d.title,{x:m,y:i.headerY,w:c,h:i.headerHeight,fontSize:g,fontFace:n.fonts.heading,color:f?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:Ot})}d.bullets&&d.bullets.length>0&&xcr({slide:e,bullets:d.bullets,startX:m,startY:i.bulletsStartY,width:c,theme:n})})}function g0n(e,t,r,n,o,i){const s=[];r.leftColumn&&s.push(r.leftColumn),r.rightColumn&&s.push(r.rightColumn),s.length>0&&Ccr(e,t,s,o,{highlightFirstColumn:!0}),i&&!r.rightColumn?.bullets&&Jue(e,i,Gt.columnRight)}function y0n(e,t,r,n){const o=[];r.leftColumn&&o.push(r.leftColumn),r.centerColumn&&o.push(r.centerColumn),r.rightColumn&&o.push(r.rightColumn),o.length>0&&Ccr(e,t,o,n,{highlightFirstColumn:!0})}function v0n(e,t,r,n){if(e.addText("\u201C",{x:.5,y:1,w:1,h:1,fontSize:120,fontFace:"Georgia",color:n.colors.primary.replace("#",""),fit:Ot}),r.quote&&e.addText(r.quote,{x:Gt.quote.x,y:Gt.quote.y,w:Gt.quote.w,h:Gt.quote.h,fontSize:n.fonts.sizes.heading,fontFace:"Georgia",color:n.colors.text.replace("#",""),italic:!0,valign:"middle",fit:Ot}),r.quoteAuthor){let o=`\u2014 ${r.quoteAuthor}`;r.quoteAuthorTitle&&(o+=`, ${r.quoteAuthorTitle}`),e.addText(o,{x:Gt.quoteAuthor.x,y:Gt.quoteAuthor.y,w:Gt.quoteAuthor.w,h:Gt.quoteAuthor.h,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"right",fit:Ot})}}function w0n(e,t,r,n){if(Os(e,t,n),!r.statistics||r.statistics.length===0)return;const o=r.statistics.slice(0,4),i=9/o.length;o.forEach((s,a)=>{const l=.5+a*i;if(e.addText(s.value,{x:l,y:Gt.statRow.y,w:i-.2,h:1.2,fontSize:48,fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",fit:Ot}),e.addText(s.label,{x:l,y:Gt.statRow.y+1.3,w:i-.2,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),align:"center",fit:Ot}),s.change||s.trend){const c=s.trend==="up"?"22C55E":s.trend==="down"?"EF4444":n.colors.muted.replace("#",""),u=s.trend==="up"?"(+)":s.trend==="down"?"(-)":"";e.addText(`${u} ${s.change||""}`,{x:l,y:Gt.statRow.y+1.8,w:i-.2,h:.4,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:c,align:"center",fit:Ot})}})}function b0n(e,t,r,n,o){if(Os(e,t,o),!r.chartData||!r.chartData.series||r.chartData.series.length===0){e.addText("No chart data available",{x:Gt.chart.x,y:Gt.chart.y+1,w:Gt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:Ot});return}const i=r.chartData.series.filter(l=>l.name&&Array.isArray(l.labels)&&l.labels.length>0&&Array.isArray(l.values)&&l.values.length>0);if(i.length===0){e.addText("Invalid chart data format",{x:Gt.chart.x,y:Gt.chart.y+1,w:Gt.chart.w,h:1,fontSize:18,color:o.colors.muted.replace("#",""),align:"center",fit:Ot});return}const s=d0n(n),a=i.map(l=>({name:l.name,labels:l.labels,values:l.values}));e.addChart(s,a,{x:Gt.chart.x,y:Gt.chart.y,w:Gt.chart.w,h:Gt.chart.h,showTitle:!!r.chartData.title,title:r.chartData.title,showLegend:r.chartData.legendPosition!=="none",legendPos:Pcr[r.chartData.legendPosition||"bottom"]||"b",showValue:r.chartData.showLabels,chartColors:[o.colors.primary.replace("#",""),o.colors.secondary.replace("#",""),o.colors.accent.replace("#","")]})}function T0n(e,t,r,n){if(Os(e,t,n),!r.tableData)return;const{headers:o,rows:i,hasHeader:s}=r.tableData,a=[];s&&o&&a.push(o.map(l=>({text:l,options:{bold:!0,fill:{color:n.colors.primary.replace("#","")},color:n.colors.textOnPrimary.replace("#",""),align:"center"}}))),i.forEach((l,c)=>{a.push(l.map(u=>({text:u.text,options:{fill:{color:c%2===0?"F8FAFC":"FFFFFF"},color:n.colors.text.replace("#",""),align:u.align||"left"}})))}),e.addTable(a,{x:Gt.chart.x,y:Gt.chart.y,w:Gt.chart.w,colW:Array(o?.length||i[0]?.length||1).fill(Gt.chart.w/(o?.length||i[0]?.length||1)),fontSize:n.fonts.sizes.body-2,fontFace:n.fonts.body,border:{pt:.5,color:"E2E8F0"},autoPage:!0}),r.tableData.caption&&e.addText(r.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 _0n(e,t,r,n){if(Os(e,t,n),!r.timeline?.items)return;const o=r.timeline.items.slice(0,5);r.timeline.orientation!=="vertical"?E0n(e,o,n):S0n(e,o,n)}function E0n(e,t,r){const n=8/t.length,o=2.8;e.addShape("rect",{x:1,y:o,w:8,h:.02,fill:{color:r.colors.primary.replace("#","")}}),t.forEach((i,s)=>{const a=1+s*n+n/2-.15;e.addShape("ellipse",{x:a,y:o-.15,w:.3,h:.3,fill:{color:r.colors.primary.replace("#","")}}),e.addText(i.date,{x:a-n/2+.15,y:o-.8,w:n,h:.4,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.primary.replace("#",""),align:"center",bold:!0,fit:Ot}),e.addText(i.title,{x:a-n/2+.15,y:o+.4,w:n,h:.4,fontSize:r.fonts.sizes.body,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),align:"center",bold:!0,fit:Ot}),i.description&&e.addText(i.description,{x:a-n/2+.15,y:o+.85,w:n,h:.8,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.muted.replace("#",""),align:"center",fit:Ot})})}function S0n(e,t,r){const n=3/t.length,o=1.5;e.addShape("rect",{x:o,y:1.5,w:.04,h:3.5,fill:{color:r.colors.primary.replace("#","")}}),t.forEach((i,s)=>{const a=1.7+s*n;e.addShape("ellipse",{x:o-.12,y:a,w:.28,h:.28,fill:{color:r.colors.primary.replace("#","")}}),e.addText(i.date,{x:.3,y:a-.1,w:1,h:.3,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.primary.replace("#",""),bold:!0,fit:Ot}),e.addText(i.title,{x:2,y:a-.1,w:7,h:.4,fontSize:r.fonts.sizes.body,fontFace:r.fonts.heading,color:r.colors.text.replace("#",""),bold:!0,fit:Ot}),i.description&&e.addText(i.description,{x:2,y:a+.3,w:7,h:.4,fontSize:r.fonts.sizes.caption,fontFace:r.fonts.body,color:r.colors.muted.replace("#",""),fit:Ot})})}function k0n(e,t,r,n){if(Os(e,t,n),!r.processSteps)return;const o=r.processSteps.slice(0,5),i=8/o.length;o.forEach((s,a)=>{const l=1+a*i,c=i-.4;e.addShape("roundRect",{x:l,y:2,w:c,h:2,fill:{color:n.colors.primary.replace("#","")},rectRadius:.1}),e.addText(String(s.step),{x:l,y:2.1,w:c,h:.5,fontSize:24,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:Ot}),e.addText(s.title,{x:l,y:2.6,w:c,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.textOnPrimary.replace("#",""),align:"center",bold:!0,fit:Ot}),s.description&&e.addText(s.description,{x:l,y:3.2,w:c,h:.7,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.textOnPrimary.replace("#",""),align:"center",fit:Ot}),a<o.length-1&&e.addShape("rightArrow",{x:l+c+.02,y:2.85,w:.35,h:.3,fill:{color:n.colors.primary.replace("#","")}})})}function x0n(e,t,r,n){if(Os(e,t,n,!1),!r.comparison?.columns)return;const o=r.comparison.columns.slice(0,2),i=4.2,s=2,l=5-s,c=Math.max(...o.map(p=>Math.min(p.items?.length||0,6))),u=c>0?Math.min(.7,(l-ST*c)/c):.5,d=u+ST;o.forEach((p,m)=>{const f=.5+m*4.8;e.addShape("roundRect",{x:f,y:1.4,w:i,h:.5,fill:{color:p.highlight?n.colors.primary.replace("#",""):n.colors.muted.replace("#","")},rectRadius:.05}),e.addText(p.title,{x:f,y:1.4,w:i,h:.5,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:p.highlight?n.colors.textOnPrimary.replace("#",""):n.colors.text.replace("#",""),align:"center",bold:!0,valign:"middle",fit:Ot});const g=(p.items||[]).slice(0,6),y=g.length>4?Math.max(12,n.fonts.sizes.body-2):n.fonts.sizes.body;g.forEach((v,w)=>{if(bT(v)){const b=wT(v),E=[{text:"\u2022 ",options:{fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#","")}},...TT(b,{fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#","")})];e.addText(E,{x:f+.2,y:s+w*d,w:i-.4,h:u,valign:"top",fit:Ot})}else e.addText(`\u2022 ${v}`,{x:f+.2,y:s+w*d,w:i-.4,h:u,fontSize:y,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top",fit:Ot})})})}function A0n(e,t,r,n){Os(e,t,n);const o=r.features||[],i=r.icons||[],s=o.length>0?o:i.map(c=>({title:c.label,description:c.description||"",icon:c.icon}));if(s.length===0)return;const a=Math.min(s.length,3),l=9/a;s.slice(0,6).forEach((c,u)=>{const d=Math.floor(u/a),m=.5+u%a*l,f=1.6+d*1.8;if(c.icon){const g=parseInt(c.icon,16);if(!Number.isNaN(g)&&g>=0&&g<=1114111){const y=String.fromCodePoint(g);e.addText(y,{x:m,y:f,w:l-.2,h:.6,fontSize:36,fontFace:"Segoe UI Emoji",color:n.colors.primary.replace("#",""),align:"center",fit:Ot})}}e.addText(c.title,{x:m,y:f+.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:Ot}),c.description&&e.addText(c.description,{x:m,y:f+1,w:l-.2,h:.6,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:Ot})})}function C0n(e,t,r,n){if(Os(e,t,n),!r.teamMembers)return;const o=r.teamMembers.slice(0,4),i=9/o.length;o.forEach((s,a)=>{const l=.5+a*i;e.addShape("ellipse",{x:l+(i-1.5)/2,y:1.6,w:1.5,h:1.5,fill:{color:n.colors.muted.replace("#","")}});const c=s.name.split(" ").map(u=>u[0]).join("").substring(0,2);e.addText(c,{x:l+(i-1.5)/2,y:2,w:1.5,h:.7,fontSize:28,fontFace:n.fonts.heading,color:"FFFFFF",align:"center",bold:!0,fit:Ot}),e.addText(s.name,{x:l,y:3.3,w:i-.2,h:.4,fontSize:n.fonts.sizes.body,fontFace:n.fonts.heading,color:n.colors.text.replace("#",""),align:"center",bold:!0,fit:Ot}),e.addText(s.role,{x:l,y:3.7,w:i-.2,h:.3,fontSize:n.fonts.sizes.caption,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",fit:Ot})})}function I0n(e,t,r,n){if(Os(e,t,n),r.bullets){const o=r.bullets.map(i=>({...i,icon:i.icon||"2713"}));Acr(e,o,Gt.contentFull,n,"conclusion")}r.cta&&e.addText(r.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:Ot})}function ET(e,t,r,n,o=!1){e.addShape("roundRect",{x:t.x,y:t.y,w:t.w,h:t.h,fill:{color:o?n.colors.primary.replace("#","")+"15":"F8F9FA"},line:{color:o?n.colors.primary.replace("#",""):"E5E7EB",width:1},rectRadius:.1});let i=t.y+.15,s=t.h-.3;return r&&(e.addText(r,{x:t.x+.15,y:t.y+.1,w:t.w-.3,h:.35,fontSize:14,fontFace:n.fonts.heading,color:o?n.colors.primary.replace("#",""):n.colors.text.replace("#",""),bold:!0,fit:Ot}),i=t.y+.45,s=t.h-.55),{contentY:i,contentH:s}}function Icr(e,t,r,n,o,i){if(!t||t.length===0)return;const s=Math.max(11,Math.min(14,16-t.length)),a=n.colors.text.replace("#","");t.forEach((l,c)=>{if(!l||!l.text)return;const u=o+c*(i/t.length);if(bT(l.text)){const d=wT(l.text),p=[{text:"\u2022 ",options:{fontSize:s,fontFace:n.fonts.body,color:a}},...TT(d,{fontSize:s,fontFace:n.fonts.body,color:a})];e.addText(p,{x:r.x+.15,y:u,w:r.w-.3,h:i/t.length,valign:"top",fit:Ot})}else e.addText(`\u2022 ${l.text}`,{x:r.x+.15,y:u,w:r.w-.3,h:i/t.length,fontSize:s,fontFace:n.fonts.body,color:a,valign:"top",fit:Ot})})}function Yue(e,t,r,n,o,i){e.addText(t.value,{x:r.x,y:o,w:r.w,h:i*.6,fontSize:Math.min(32,r.w*8),fontFace:n.fonts.heading,color:n.colors.primary.replace("#",""),bold:!0,align:"center",valign:"bottom",fit:Ot}),e.addText(t.label,{x:r.x,y:o+i*.6,w:r.w,h:i*.4,fontSize:11,fontFace:n.fonts.body,color:n.colors.muted.replace("#",""),align:"center",valign:"top",fit:Ot})}function Rcr(e){const{slide:t,icon:r,label:n,description:o,pos:i,theme:s,contentY:a,contentH:l}=e,c=Math.min(.6,i.w*.2);t.addShape("ellipse",{x:i.x+(i.w-c)/2,y:a,w:c,h:c,fill:{color:s.colors.primary.replace("#","")}});const u=parseInt(r,16);if(Number.isNaN(u)||u<0||u>1114111){h.warn("[renderIconBoxInZone] Invalid icon code",{icon:r});return}const d=String.fromCodePoint(u);t.addText(d,{x:i.x+(i.w-c)/2,y:a,w:c,h:c,fontSize:16,color:"FFFFFF",align:"center",valign:"middle",fit:Ot}),t.addText(n,{x:i.x,y:a+c+.1,w:i.w,h:.3,fontSize:12,fontFace:s.fonts.heading,color:s.colors.text.replace("#",""),bold:!0,align:"center",fit:Ot}),o&&t.addText(o,{x:i.x+.1,y:a+c+.4,w:i.w-.2,h:l-c-.5,fontSize:10,fontFace:s.fonts.body,color:s.colors.muted.replace("#",""),align:"center",fit:Ot})}function Mcr(e,t,r,n,o,i){const s=t.type==="pie"?"pie":t.type==="line"?"line":"bar",a=t.series||[];if(a.length===0)return;const l=a.map(c=>({name:c.name||"Data",labels:c.labels||[],values:c.values||[]}));try{e.addChart(s,l,{x:r.x+.1,y:o,w:r.w-.2,h:i,showLegend:!1,showTitle:!1,chartColors:[n.colors.primary.replace("#",""),n.colors.secondary.replace("#",""),n.colors.accent.replace("#",""),n.colors.muted.replace("#","")]})}catch{e.addText("Chart",{x:r.x,y:o,w:r.w,h:i,fontSize:14,color:n.colors.muted.replace("#",""),align:"center",valign:"middle",fit:Ot})}}function R0n(e,t,r,n){Os(e,t,n,!1);const o=Zs[r.layout]||Zs["left-right"];(r.zones||[]).forEach((s,a)=>{if(a>=o.length)return;const l=o[a],{contentY:c,contentH:u}=ET(e,l,s.title,n,s.isPrimary);switch(s.type){case"bullets":Array.isArray(s.data)&&Icr(e,s.data,l,n,c,u);break;case"stats":s.data&&typeof s.data=="object"&&Yue(e,s.data,l,n,c,u);break;case"icon-box":if(s.data&&typeof s.data=="object"){const d=s.data;Rcr({slide:e,icon:d.icon,label:d.label,description:d.description,pos:l,theme:n,contentY:c,contentH:u})}break;case"chart":s.data&&typeof s.data=="object"&&Mcr(e,s.data,l,n,c,u);break;case"text-box":typeof s.data=="string"&&e.addText(s.data,{x:l.x+.15,y:c,w:l.w-.3,h:u,fontSize:12,fontFace:n.fonts.body,color:n.colors.text.replace("#",""),valign:"top"});break}})}function M0n(e,t,r,n){if(Os(e,t,n,!1),r.bullets&&r.bullets.length>0){const o=Zs["left-right"][0],{contentY:i,contentH:s}=ET(e,o,r.leftColumn?.title,n,!0);Icr(e,r.bullets,o,n,i,s)}if(r.chartData){const o=Zs["left-right"][1],{contentY:i,contentH:s}=ET(e,o,"Data",n,!1);Mcr(e,r.chartData,o,n,i,s)}else if(r.statistics&&r.statistics.length>0){const o=Zs["left-right"][1];ET(e,o,"Metrics",n,!1);const i=r.statistics.slice(0,3),s=o.h/i.length;i.forEach((a,l)=>{Yue(e,a,{...o,y:o.y+l*s,h:s},n,o.y+l*s+.1,s-.2)})}}function P0n(e,t,r,n){Os(e,t,n,!1);const o=r.statistics||[];if(o.length===0)return;let i;o.length<=2?i=Zs["left-right"]:o.length<=3?i=Zs["three-cols"]:o.length<=4?i=Zs.quadrants:o.length<=5?i=Zs["five-boxes"]:i=Zs["six-boxes"],o.slice(0,i.length).forEach((s,a)=>{const l=i[a],c=a===0,{contentY:u,contentH:d}=ET(e,l,void 0,n,c);Yue(e,s,l,n,u,d)})}function O0n(e,t,r,n){Os(e,t,n,!1);const o=r.icons||r.features||[];if(o.length===0)return;let i;o.length<=2?i=Zs["left-right"]:o.length<=3?i=Zs["three-cols"]:o.length<=4?i=Zs.quadrants:o.length<=5?i=Zs["five-boxes"]:i=Zs["six-boxes"],o.slice(0,i.length).forEach((s,a)=>{const l=i[a],c=a===0,{contentY:u,contentH:d}=ET(e,l,void 0,n,c),p=s.icon||"1F4A1",m=s.title||s.label||"",f=s.description;Rcr({slide:e,icon:p,label:m,description:f,pos:l,theme:n,contentY:u,contentH:d})})}var ST,Ot,Gt,Pcr,Zs,D0n=S({"src/lib/features/ppt/slideRenderers.ts"(){"use strict";z(),vT(),Kue(),ST=.1,Ot="shrink",Gt={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}},Pcr={top:"t",bottom:"b",left:"l",right:"r"},Zs={"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}]}}});async function N0n(){if($C)return $C;const t=(await Al("pptxgenjs","PPT generation")).default;return $C=typeof t=="function"?t:t.default,$C}var $C,Ocr,Dcr=S({async"src/lib/features/ppt/slideGenerator.ts"(){"use strict";Mx(),hn(),lt(),vT(),z(),gd(),et(),Zn(),D0n(),$C=null,Ocr=class{theme;config;neurolink;imageLimit;userImageIndex=0;constructor(e){this.config=e,this.theme=typeof e.theme=="string"?qlr(e.theme):e.theme,this.neurolink=e.neurolink||null,this.imageLimit=qg(jue)}getNextUserImage(){const e=this.config.userImages;if(!e||e.length===0)return;const 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://")){const n=await Be(fetch(e),15e3,ve.toolTimeout("userImageFetch",15e3));if(!n.ok){h.warn(`[SlideGenerator] Failed to fetch user image: ${e}`);return}return Buffer.from(await n.arrayBuffer())}return await(await Promise.resolve().then(()=>(yi(),zg))).readFile(e)}catch(r){h.warn("[SlideGenerator] Failed to load user image",{error:r instanceof Error?r.message:String(r)});return}}async generateSlide(e){const t=Ce.createSpan("ppt.generation","ppt.generateSlide",{"ppt.operation":"generateSlide","ppt.slideIndex":e.slideNumber,"ppt.theme":this.theme.name}),r=Date.now();try{let n,o;if(x$(e.type)){const a=this.getNextUserImage();if(a&&(h.info(`[SlideGenerator] \u{1F4F7} Using user-provided image for slide ${e.slideNumber}: "${e.title}"`),n=await this.loadUserImage(a),n&&(o={prompt:"User-provided image",model:"user-upload",generatedAt:new Date})),!n&&this.config.generateAIImages&&e.imagePrompt){h.info(`[SlideGenerator] \u23F3 Generating AI image for slide ${e.slideNumber}: "${e.title}"...`);const l=await this.generateImage(e.imagePrompt,e.type);l&&(n=l.buffer,o={prompt:e.imagePrompt,model:l.model,generatedAt:new Date})}}const i=Date.now()-r;h.debug(`[SlideGenerator] Generated slide ${e.slideNumber} (${e.type})`,{hasImage:!!n,generationTime:i});const s=Ce.endSpan(t,1);return rt().recordSpan(s),{slideNumber:e.slideNumber,schema:e,imageBuffer:n,imageMetadata:o,generationTime:i}}catch(n){const o=Ce.endSpan(t,2);o.statusMessage=n instanceof Error?n.message:String(n),rt().recordSpan(o);const i=n instanceof Me?n:ve.toolExecutionFailed("slideGenerator",n instanceof Error?n:new Error(String(n)));return h.error(`[SlideGenerator] Failed to generate slide ${e.slideNumber}`,{error:i.message,type:e.type}),{slideNumber:e.slideNumber,schema:e,generationTime:Date.now()-r}}}async generateSlides(e){const t=Date.now(),r=this.config.generateAIImages?e.filter(c=>c.imagePrompt&&x$(c.type)).length:0,n=this.config.userImages?.length??0;h.info(`[SlideGenerator] Generating ${e.length} slides...`,{theme:this.theme.name,generateAIImages:this.config.generateAIImages,slidesNeedingAIImages:r,userImagesProvided:n}),this.userImageIndex=0;const o=e.map(c=>this.imageLimit(()=>this.generateSlide(c))),i=await Promise.all(o),s=i.filter(c=>c.imageBuffer).length,a=this.config.generateAIImages?e.filter(c=>c.imagePrompt&&x$(c.type)&&!i.find(u=>u.slideNumber===c.slideNumber)?.imageBuffer).length:0,l=Date.now()-t;return h.info("[SlideGenerator] Slide generation complete",{totalSlides:i.length,totalImages:s,failedImages:a,generationTime:l}),{slides:i,totalImages:s,failedImages:a,generationTime:l}}renderSlide(e,t,r,n){const{schema:o,imageBuffer:i}=t,s=e.addSlide();return this.applyBackground(s,o.type),this.applyLayout(s,o,i),o.type!=="title"&&o.type!=="thank-you"&&this.addSlideNumber(s,r,n),this.addLogo(s,o.type),o.speakerNotes&&s.addNotes(o.speakerNotes),s}async generateImage(e,t){if(!this.neurolink)return h.warn("[SlideGenerator] No NeuroLink instance provided, skipping image generation"),null;try{const r=Hlr(e,this.theme.name);h.debug(`[SlideGenerator] Generating image for ${t}`,{promptPreview:r.substring(0,100)});const n=await Be(this.neurolink.generate({input:{text:r},provider:this.config.provider||"vertex",model:this.config.imageModel||"gemini-2.5-flash-image"}),P$,ve.toolTimeout("imageGeneration",P$));if(!n||!n.imageOutput?.base64)return h.warn(`[SlideGenerator] No image data returned for ${t}`),null;const o=Buffer.from(n.imageOutput.base64,"base64");return o.length<100?(h.warn(`[SlideGenerator] Image buffer too small (${o.length} bytes) for ${t}`),null):(o[0]===255&&o[1]===216&&o[2]===255||o[0]===137&&o[1]===80&&o[2]===78&&o[3]===71||o[0]===71&&o[1]===73&&o[2]===70||o[0]===82&&o[1]===73&&o[2]===70&&o[3]===70||h.warn(`[SlideGenerator] Unknown image format for ${t}, magic bytes: ${o.slice(0,4).toString("hex")}`),h.debug(`[SlideGenerator] Image generated successfully for ${t}`,{size:o.length,format:o[0]===255?"JPEG":o[0]===137?"PNG":o[0]===71?"GIF":"unknown"}),{buffer:o,model:n.model||this.config.imageModel})}catch(r){const n=r instanceof Me?r:ve.toolExecutionFailed("imageGeneration",r instanceof Error?r:new Error(String(r)));return h.error("[SlideGenerator] Image generation failed",{error:n.message,slideType:t}),null}}applyBackground(e,t){e.background={color:this.theme.colors.background.replace("#","")}}applyLayout(e,t,r){const{type:n,layout:o,title:i,content:s}=t;switch(n){case"title":p0n(e,i,s,this.theme,r);break;case"section-header":m0n(e,i,s,this.theme);break;case"content":case"bullets":case"agenda":case"numbered-list":Xue({slide:e,title:i,content:s,layout:o,theme:this.theme,imageBuffer:r,slideType:n});break;case"image-focus":case"image-left":case"image-right":case"full-bleed-image":f0n(e,i,s,o,this.theme,r);break;case"two-column":case"split-content":g0n(e,i,s,o,this.theme,r);break;case"three-column":y0n(e,i,s,this.theme);break;case"quote":v0n(e,i,s,this.theme);break;case"statistics":w0n(e,i,s,this.theme);break;case"chart-bar":case"chart-line":case"chart-pie":case"chart-area":b0n(e,i,s,n,this.theme);break;case"table":T0n(e,i,s,this.theme);break;case"timeline":_0n(e,i,s,this.theme);break;case"process-flow":k0n(e,i,s,this.theme);break;case"comparison":x0n(e,i,s,this.theme);break;case"features":case"icons":A0n(e,i,s,this.theme);break;case"team":C0n(e,i,s,this.theme);break;case"conclusion":I0n(e,i,s,this.theme);break;case"thank-you":case"closing":h0n(e,i,s,this.theme,r);break;case"dashboard":s.dashboard&&R0n(e,i,s.dashboard,this.theme);break;case"mixed-content":M0n(e,i,s,this.theme);break;case"stats-grid":P0n(e,i,s,this.theme);break;case"icon-grid":O0n(e,i,s,this.theme);break;case"blank":break;default:Xue({slide:e,title:i,content:s,layout:o,theme:this.theme,imageBuffer:r,slideType:n})}}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(ws(e)){const t=sp(e),r=e.split(".").pop()?.toLowerCase();return`data:${r==="svg"?"image/svg+xml":r==="jpg"||r==="jpeg"?"image/jpeg":"image/png"};base64,${t.toString("base64")}`}}catch{h.warn("[SlideGenerator] Could not read logo file, treating as base64")}return`data:image/png;base64,${e}`}addLogo(e,t){const r=this.getLogoConfig();if(!r)return;const n=r.showOn||"all-slides";if(n==="title-only"&&t!=="title"||n==="title-and-closing"&&t!=="title"&&t!=="thank-you"&&t!=="closing")return;const o=this.getLogoDataUri(r.data),i=r.position||"bottom-right",s=r.width||1,a=r.height||.4;let l,c;const u=Gt.logo;if(i==="title-only"?(l=u["bottom-right"].x,c=u["bottom-right"].y):(l=u[i].x,c=u[i].y),i==="top-right"||i==="bottom-right"){const{width:d}=_P[this.config.aspectRatio];l=d-s-.3}if(i==="bottom-left"||i==="bottom-right"){const{height:d}=_P[this.config.aspectRatio];c=d-a-.2}e.addImage({data:o,x:l,y:c,w:s,h:a,sizing:{type:"contain",w:s,h:a}})}addSlideNumber(e,t,r){e.addText(`${t} / ${r}`,{x:Gt.footer.x,y:Gt.footer.y,w:Gt.footer.w,h:Gt.footer.h,fontSize:this.theme.fonts.sizes.caption,fontFace:this.theme.fonts.body,color:this.theme.colors.muted.replace("#",""),align:"right"})}}}});function L0n(e){const t=e.trim();for(const{patterns:r,slideType:n,bulletStyle:o}of Lcr)for(const i of r)if(i.test(t))return{slideType:n,bulletStyle:o};return{slideType:null,bulletStyle:null}}function F0n(e){if(!e||e.length===0)return null;for(const t of e)for(const{pattern:r,bulletStyle:n}of Fcr)if(r.test(t.text))return n;return null}function Ncr(e){switch(e){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 $0n(e,t,r){const{slideType:n,bulletStyle:o}=L0n(e);if(n)return{type:n,bulletStyle:o||Ncr(n),wasInferred:!0};const i=r.bullets?F0n(r.bullets):null;return i?{type:t,bulletStyle:i,wasInferred:!0}:{type:t,bulletStyle:Ncr(t),wasInferred:!1}}function U0n(e,t){return(e.bullets?.length??0)>0||(e.leftColumn?.bullets?.length??0)>0||(e.rightColumn?.bullets?.length??0)>0||(e.centerColumn?.bullets?.length??0)>0?{...e,bullets:e.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t})),leftColumn:e.leftColumn?{...e.leftColumn,bullets:e.leftColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0,rightColumn:e.rightColumn?{...e.rightColumn,bullets:e.rightColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0,centerColumn:e.centerColumn?{...e.centerColumn,bullets:e.centerColumn.bullets?.map(n=>({...n,bulletStyle:n.bulletStyle||t}))}:void 0}:e}var Lcr,Fcr,B0n=S({"src/lib/features/ppt/slideTypeInference.ts"(){"use strict";Lcr=[{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"}],Fcr=[{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 z0n(e,t="content"){return typeof e=="string"&&$cr.has(e)?e:(h.warn(`[ContentPlanner] Invalid slide type "${e}", using "${t}"`),t)}function G0n(e,t){if(typeof e=="string"&&Ucr.has(e))return e;const n=A$[t]?.[0]||"title-content";return h.warn(`[ContentPlanner] Invalid layout "${e}" for type "${t}", using "${n}"`),n}function q0n(e){if(e&&typeof e=="object"&&"text"in e){const t=e,r={text:String(t.text||"")};return Array.isArray(t.subBullets)&&(r.subBullets=t.subBullets.map(n=>String(n))),typeof t.icon=="string"&&(r.icon=t.icon),typeof t.emphasis=="boolean"&&(r.emphasis=t.emphasis),typeof t.fontSize=="number"&&t.fontSize>=8&&t.fontSize<=48&&(r.fontSize=t.fontSize),typeof t.bulletStyle=="string"&&Bcr.has(t.bulletStyle)&&(r.bulletStyle=t.bulletStyle),typeof t.color=="string"&&t.color.match(/^#?[0-9A-Fa-f]{6}$/)&&(r.color=t.color.startsWith("#")?t.color:`#${t.color}`),typeof t.bold=="boolean"&&(r.bold=t.bold),r.text?r:null}return typeof e=="string"&&e.trim()?{text:e.trim()}:null}function O$(e){if(!Array.isArray(e))return[];const t=[];for(const r of e){const n=q0n(r);n&&t.push(n)}return t}function j0n(e){if(!e||typeof e!="object")return{};const t=e,r={};if(t.bullets&&(r.bullets=O$(t.bullets)),t.leftColumn&&typeof t.leftColumn=="object"){const o=t.leftColumn;r.leftColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?O$(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(t.rightColumn&&typeof t.rightColumn=="object"){const o=t.rightColumn;r.rightColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?O$(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}if(t.centerColumn&&typeof t.centerColumn=="object"){const o=t.centerColumn;r.centerColumn={title:typeof o.title=="string"?o.title:void 0,bullets:o.bullets?O$(o.bullets):void 0,image:typeof o.image=="string"?o.image:void 0}}const 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(const o of n)t[o]!==void 0&&(r[o]=t[o]);return r}function V0n(e,t){if(!e||typeof e!="object")throw new Ll("AI returned invalid response: expected object",gu.INVALID_AI_RESPONSE,{received:typeof e});const r=e;if(typeof r.title!="string"||!r.title.trim())throw new Ll("AI response missing valid 'title' field",gu.INVALID_AI_RESPONSE,{field:"title",received:r.title});if(!Array.isArray(r.slides))throw new Ll("AI response missing 'slides' array",gu.INVALID_AI_RESPONSE,{field:"slides",received:typeof r.slides});r.slides.length!==t&&h.warn(`[ContentPlanner] AI returned ${r.slides.length} slides, expected ${t}. Adjusting...`);const n=[];for(let o=0;o<r.slides.length;o++){const i=r.slides[o];if(!i||typeof i!="object")throw new Ll(`Invalid slide at index ${o}`,gu.INVALID_AI_RESPONSE,{index:o,received:typeof i});typeof i.title!="string"&&(i.title=`Slide ${o+1}`,h.warn(`[ContentPlanner] Slide ${o+1} missing title, using default`));const s=z0n(i.type,"content"),a=j0n(i.content),{type:l,bulletStyle:c,wasInferred:u}=$0n(i.title,s,a),d=u&&l!==s?l:s;u&&l!==s&&h.debug(`[ContentPlanner] Slide ${o+1} type inferred from title: "${i.title}" \u2192 ${d}`);const p=U0n(a,c),m=G0n(i.layout,d);typeof i.speakerNotes!="string"&&(i.speakerNotes=""),i.imagePrompt!==null&&typeof i.imagePrompt!="string"&&(i.imagePrompt=null),n.push({slideNumber:o+1,type:d,layout:m,title:i.title,content:p,imagePrompt:i.imagePrompt,speakerNotes:i.speakerNotes})}return{title:r.title,totalSlides:n.length,audience:r.audience||"general",tone:r.tone||"professional",theme:r.theme||"modern",slides:n,keyMessages:Array.isArray(r.keyMessages)?r.keyMessages:void 0}}function H0n(e){const t=e.trim(),r=[],n=t.match(/```(?:json)?\s*\n?([\s\S]*?)\n?```/);n&&n[1]&&r.push(n[1].trim()),t.startsWith("```")&&r.push(t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""));const o=t.indexOf("{"),i=t.indexOf("["),s=o===-1?i:i===-1?o:Math.min(o,i);if(s>0){const c=t[s]==="{"?"}":"]",u=t.lastIndexOf(c);u>s&&r.push(t.slice(s,u+1))}r.push(t);const a=[];for(const l of r)try{return JSON.parse(l)}catch(c){a.push(c instanceof Error?c.message:String(c))}throw new Ll(`Failed to parse AI response as JSON: ${a[a.length-1]}`,gu.INVALID_AI_RESPONSE,{contentPreview:e.substring(0,500),parseError:a.join(" | ")})}async function W0n(e,t){const r=Date.now(),n=`session-${Date.now()}`;h.info("[ContentPlanner] Starting content planning",{topic:e.topic.substring(0,100),pages:e.pages,audience:e.audience,tone:e.tone,theme:e.theme,generateAIImages:e.generateAIImages,provider:e.provider,model:e.model,sessionId:n});const o=Vlr({topic:e.topic,pages:e.pages,audience:e.audience,tone:e.tone,theme:e.theme,generateAIImages:e.generateAIImages,modelInfo:{name:e.model||"unknown",provider:e.provider||"auto-selected"}});try{const i=await t.generate({prompt:o,systemPrompt:Gue,temperature:.7,maxTokens:8192,disableTools:!0,timeout:que});if(!i||!i.content)throw new Ll("AI provider returned empty response",gu.PLANNING_FAILED,{provider:e.provider});const s=Date.now()-r;h.debug("[ContentPlanner] AI response received",{contentLength:i.content.length,planningTime:s});const a=H0n(i.content),l=V0n(a,e.pages);return h.info("[ContentPlanner] Content plan generated successfully",{title:l.title,totalSlides:l.totalSlides,planningTime:s,keyMessages:l.keyMessages?.length||0}),l}catch(i){if(i instanceof Ll)throw i;const s=i instanceof Error?i.message:String(i);throw new Ll(`Content planning failed: ${s}`,gu.PLANNING_FAILED,{topic:e.topic.substring(0,100),provider:e.provider},i instanceof Error?i:void 0)}}function K0n(e){return e.slides.length>0&&e.slides[0].type!=="title"&&(e.slides[0]={...e.slides[0],type:"title",layout:"title-centered"}),e}function J0n(e){const t=e.slides.length-1;return t>=0&&e.slides[t].type!=="thank-you"&&(e.slides[t]={...e.slides[t],type:"thank-you",layout:"contact-info"}),e}function X0n(e){let t={...e,slides:[...e.slides]};return t=K0n(t),t=J0n(t),t}var $cr,Ucr,Bcr,Y0n=S({"src/lib/features/ppt/contentPlanner.ts"(){"use strict";Vue(),vT(),B0n(),z(),$cr=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"]),Ucr=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"]),Bcr=new Set(["disc","number","checkmark","arrow","dash","none"])}}),zcr={};ce(zcr,{generatePresentation:()=>Z0n});async function Z0n(e){const t=Ce.createSpan("ppt.generation","ppt.orchestrate",{"ppt.operation":"orchestrate","ppt.slideCount":e.context.pages,"ppt.theme":typeof e.context.theme=="string"?e.context.theme:"custom"}),r={startTime:Date.now(),contentPlan:null,slides:null,outputPath:null},{context:n,provider:o,providerName:i,modelName:s,neurolink:a,imageProvider:l,imageModel:c}=e;h.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{h.info("[PresentationOrchestrator] Step 1: Content planning...");const u=await Be(W0n(n,o),xc/2,ve.toolTimeout("contentPlanning",xc/2));r.contentPlan=X0n(u),t.attributes["ppt.slideCount"]=r.contentPlan.totalSlides,t.attributes["ppt.theme"]=typeof r.contentPlan.theme=="string"?r.contentPlan.theme:"custom",h.info("[PresentationOrchestrator] Content plan ready",{title:r.contentPlan.title,totalSlides:r.contentPlan.totalSlides,theme:r.contentPlan.theme,audience:r.contentPlan.audience,tone:r.contentPlan.tone}),h.info("[PresentationOrchestrator] Step 2: Generating slides...");const d=n.logo??null,p=_cr(d),f={theme:r.contentPlan.theme||n.theme,generateAIImages:n.generateAIImages,aspectRatio:n.aspectRatio,provider:l??n.provider??"vertex",imageModel:c??"gemini-2.5-flash-image",logo:p??void 0,userImages:n.images,neurolink:a},g=new Ocr(f),y=await Be(g.generateSlides(r.contentPlan.slides),xc/2,ve.toolTimeout("slideGeneration",xc/2));r.slides=y.slides,h.info("[PresentationOrchestrator] Slides generated",{totalSlides:r.slides.length,totalImages:y.totalImages,failedImages:y.failedImages,generationTime:y.generationTime}),h.info("[PresentationOrchestrator] Step 3: Assembling PPTX...");const v=await N0n(),w=new v;w.title=r.contentPlan.title,w.subject=`Generated presentation about: ${n.topic.substring(0,100)}`,w.author="NeuroLink PPT Generator",w.company="NeuroLink",w.layout=Ecr(n.aspectRatio);const b=[...r.slides].sort((P,O)=>P.slideNumber-O.slideNumber);for(let P=0;P<b.length;P++){const O=b[P];g.renderSlide(w,O,P+1,b.length)}h.info("[PresentationOrchestrator] PPTX assembled",{totalSlides:b.length,layout:w.layout,title:w.title}),h.info("[PresentationOrchestrator] Step 4: Writing file..."),r.outputPath=vcr(n),await Be(wcr(r.outputPath),xc/4,ve.toolTimeout("outputDirectory",xc/4)),await Be(w.writeFile({fileName:r.outputPath}),xc/4,ve.toolTimeout("pptxWrite",xc/4));let E=0;try{E=(await Be(ko(r.outputPath),xc/8,ve.toolTimeout("pptxStat",xc/8))).size}catch{h.warn("[PresentationOrchestrator] Could not get file size")}const k=Date.now()-r.startTime;h.info("[PresentationOrchestrator] Presentation generation complete",{filePath:r.outputPath,fileSize:E,totalSlides:b.length,totalTime:k});const x=Ce.endSpan(t,1);rt().recordSpan(x),a?.recordMetricsSpan(x);const A=r.contentPlan?.theme||n.theme,R=r.contentPlan?.audience||n.audience,C=r.contentPlan?.tone||n.tone;return{filePath:r.outputPath,totalSlides:b.length,format:"pptx",provider:i,model:s,metadata:{theme:A,audience:R,tone:C,imageModel:n.generateAIImages?c??"gemini-2.5-flash-image":"",fileSize:E>0?E:0}}}catch(u){const d=Ce.endSpan(t,2);if(d.statusMessage=u instanceof Error?u.message:String(u),rt().recordSpan(d),a?.recordMetricsSpan(d),u instanceof Ll)throw h.error("[PresentationOrchestrator] Generation failed",{error:u.message,code:u.code,context:u.context}),u;const p=Scr(u);throw h.error("[PresentationOrchestrator] Unexpected error",{error:p.message,stage:Hue(r)}),new Ll(`Presentation generation failed: ${p.message}`,gu.ASSEMBLY_FAILED,{topic:n.topic.substring(0,100),stage:Hue(r),elapsedTime:Date.now()-r.startTime},p)}}var Q0n=S({async"src/lib/features/ppt/presentationOrchestrator.ts"(){"use strict";await Dcr(),yi(),Vue(),Y0n(),await Dcr(),vT(),z(),et(),Zn(),Kue()}}),Gcr={};ce(Gcr,{MUSIC_ERROR_CODES:()=>Yt,MusicError:()=>Kt,MusicProcessor:()=>Gp});var Yt,Kt,Gp,qp=S({"src/lib/utils/musicProcessor.ts"(){"use strict";Zn(),et(),z(),bw(),Yt={PROVIDER_NOT_SUPPORTED:"MUSIC_PROVIDER_NOT_SUPPORTED",PROVIDER_NOT_CONFIGURED:"MUSIC_PROVIDER_NOT_CONFIGURED",GENERATION_FAILED:"MUSIC_GENERATION_FAILED",POLL_TIMEOUT:"MUSIC_POLL_TIMEOUT",PROMPT_REQUIRED:"MUSIC_PROMPT_REQUIRED",DURATION_INVALID:"MUSIC_DURATION_INVALID",INVALID_INPUT:"MUSIC_INVALID_INPUT"},Kt=class extends Me{constructor(e){super({code:e.code,message:e.message,category:e.category??"execution",severity:e.severity??"high",retriable:e.retriable??!1,context:e.context,originalError:e.originalError}),this.name="MusicError"}},Gp=class{static registry=new Fg("MusicProcessor");static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),h.debug(`[MusicProcessor] Registered music handler: ${r}`)}static supports(e){return this.registry.supports(e)}static listProviders(){return this.registry.list()}static getHandler(e){return this.registry.get(e)}static clearHandlers(){this.registry.clear()}static buildSpanAttributes(e,t){return{"music.operation":"generate","music.provider":e,"music.duration":t.duration,"music.format":t.format,"music.genre":t.genre,"music.mood":t.mood}}static async generate(e,t){const r=Ce.createSpan("media.generation","music.generate",this.buildSpanAttributes(e,t));try{const n=t.prompt?.trim();if(!n)throw new Kt({code:Yt.PROMPT_REQUIRED,message:"Music generation requires a non-empty prompt",category:"validation",severity:"low",retriable:!1,context:{provider:e}});const o=this.getHandler(e);if(!o)throw new Kt({code:Yt.PROVIDER_NOT_SUPPORTED,message:`Music provider "${e}" is not registered. Available: ${this.listProviders().join(", ")}`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!o.isConfigured())throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:`Music provider "${e}" is not configured. Set the required credentials.`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});if(t.duration!==void 0&&o.maxDurationSeconds!==void 0&&t.duration>o.maxDurationSeconds)throw new Kt({code:Yt.DURATION_INVALID,message:`Requested duration (${t.duration}s) exceeds provider maximum (${o.maxDurationSeconds}s) for "${e}"`,category:"validation",severity:"medium",retriable:!1,context:{provider:e,requested:t.duration,maximum:o.maxDurationSeconds}});h.debug(`[MusicProcessor] Starting music generation with provider: ${e}`);const i=await o.generate({...t,prompt:n}),s=Ce.endSpan(r,1);return rt().recordSpan(s),h.info(`[MusicProcessor] Generated ${i.size} bytes (${e})`),i}catch(n){const o=Ce.endSpan(r,2,n instanceof Error?n.message:String(n));if(rt().recordSpan(o),n instanceof Kt)throw n;const i=n instanceof Error?n.message:String(n);throw new Kt({code:Yt.GENERATION_FAILED,message:`Music generation failed for provider "${e}": ${i}`,category:"execution",severity:"high",retriable:!0,context:{provider:e,duration:t.duration,format:t.format,genre:t.genre,mood:t.mood,tempo:t.tempo},originalError:n instanceof Error?n:void 0})}}}}}),qcr,u0,jcr,Vcr,kT,Hcr=S({"src/lib/music/providers/BeatovenMusic.ts"(){"use strict";z(),qp(),Ta(),OC(),qcr="https://public-api.beatoven.ai",u0=3e4,jcr=3e3,Vcr=5*6e4,kT=class{maxDurationSeconds=300;supportedFormats=["mp3","wav"];supportedGenres=["ambient","cinematic","corporate","lo-fi","rock","pop","electronic","orchestral","folk"];apiKey;baseUrl;constructor(e){const t=(e??process.env.BEATOVEN_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.BEATOVEN_BASE_URL??qcr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:"BEATOVEN_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});const t=Date.now(),r=e.format??"mp3";this.supportedFormats.includes(r)||h.warn(`[BeatovenMusic] Format "${r}" not supported \u2014 falling back to "mp3"`);const n=this.supportedFormats.includes(r)?r:"mp3",i=(await this.submitCompose(e,n)).task_id,s=await this.pollUntilComposed(i,e.timeout??Vcr),a=s.meta?.track_url;if(!a)throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven task ${i} completed but no track_url returned`,category:"execution",severity:"high",retriable:!1,context:{taskId:i,taskResult:s}});const l=await this.downloadTrack(a),c=Date.now()-t;return h.info(`[BeatovenMusic] Generated ${l.length} bytes (${n}) in ${c}ms \u2014 task ${i}`),{buffer:l,format:n,size:l.length,duration:s.meta?.duration,provider:"beatoven",metadata:{latency:c,provider:"beatoven",model:"beatoven-default",jobId:i,trackId:s.meta?.track_id,projectId:s.meta?.project_id,requestedFormat:e.format}}}async submitCompose(e,t){const r=(e.duration??60)*1e3,n=[e.prompt];e.genre&&n.push(`Genre: ${e.genre}`),e.mood&&n.push(`Mood: ${e.mood}`),e.tempo!==void 0&&n.push(`Tempo: ${e.tempo} BPM`);const o={prompt:{text:n.join(". ")},duration:r,format:t},i=new AbortController,s=setTimeout(()=>i.abort(),u0);let a;try{a=await fetch(`${this.baseUrl}/api/v1/tracks/compose`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal})}catch(c){throw c instanceof Error&&c.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven compose request timed out after ${u0/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:c}):new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven compose network error: ${c instanceof Error?c.message:String(c)}`,category:"network",severity:"high",retriable:!0,originalError:c instanceof Error?c:void 0})}finally{clearTimeout(s)}if(!a.ok){const c=await a.text(),u=a.status===408||a.status===429||a.status>=500;throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven compose failed: ${a.status} \u2014 ${c}`,category:u?"network":"execution",severity:"high",retriable:u,context:{status:a.status,body:c}})}const l=await a.json();if(!l.task_id)throw new Kt({code:Yt.GENERATION_FAILED,message:"Beatoven compose response missing task_id",category:"execution",severity:"high",retriable:!1,context:{response:l}});return l}async pollUntilComposed(e,t){const r=Date.now();for(;Date.now()-r<t;){const n=await this.fetchTaskStatus(e);if(n.status==="composed")return n;if(n.status==="failed")throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven task ${e} failed: ${n.message??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{taskId:e,status:n}});await new Promise(o=>setTimeout(o,jcr))}throw new Kt({code:Yt.POLL_TIMEOUT,message:`Beatoven task ${e} did not complete within ${Math.round(t/1e3)}s`,category:"timeout",severity:"medium",retriable:!0,context:{taskId:e,totalTimeoutMs:t}})}async fetchTaskStatus(e){const t=new AbortController,r=setTimeout(()=>t.abort(),u0);let n;try{n=await fetch(`${this.baseUrl}/api/v1/tasks/${e}`,{method:"GET",headers:{Authorization:`Bearer ${this.apiKey}`},signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven status poll timed out after ${u0/1e3}s`,category:"network",severity:"medium",retriable:!0,originalError:o}):new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven status poll network error: ${o instanceof Error?o.message:String(o)}`,category:"network",severity:"medium",retriable:!0,originalError:o instanceof Error?o:void 0,context:{taskId:e}})}finally{clearTimeout(r)}if(!n.ok){const o=await n.text();throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven status request failed: ${n.status} \u2014 ${o}`,category:"execution",severity:"medium",retriable:n.status>=500,context:{status:n.status,taskId:e}})}return await n.json()}async downloadTrack(e){try{await PC(e)}catch(o){throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track URL rejected: ${o instanceof Error?o.message:String(o)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=new AbortController,r=setTimeout(()=>t.abort(),u0);let n;try{n=await fetch(e,{signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track download timed out after ${u0/1e3}s`,category:"network",severity:"medium",retriable:!0,originalError:o}):new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track download network error: ${o instanceof Error?o.message:String(o)}`,category:"network",severity:"medium",retriable:!0,originalError:o instanceof Error?o:void 0,context:{url:e}})}finally{clearTimeout(r)}if(!n.ok)throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track download failed: ${n.status}`,category:"network",severity:"medium",retriable:n.status>=500,context:{status:n.status,url:e}});try{return await l0(n,Vh,"Beatoven track")}catch(o){throw new Kt({code:Yt.GENERATION_FAILED,message:`Beatoven track download exceeded size limit: ${o instanceof Error?o.message:String(o)}`,category:"execution",severity:"high",retriable:!1,context:{url:e}})}}}}}),Wcr,Zue,xT,Kcr=S({"src/lib/music/providers/ElevenLabsMusic.ts"(){"use strict";qp(),z(),Ta(),Wcr="https://api.elevenlabs.io/v1",Zue=6e4,xT=class{maxDurationSeconds=22;supportedFormats=["mp3"];supportedGenres=["ambient","cinematic","lo-fi","electronic","orchestral","soundscape"];apiKey;baseUrl;constructor(e){const t=(e??process.env.ELEVENLABS_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.ELEVENLABS_BASE_URL??Wcr).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:"ELEVENLABS_API_KEY not configured (shared with ElevenLabs TTS \u2014 same account, different endpoint)",category:"configuration",severity:"high",retriable:!1});const t=e.prompt?.trim();if(!t)throw new Kt({code:Yt.INVALID_INPUT,message:"ElevenLabs Music requires a non-empty prompt",category:"validation",severity:"low",retriable:!1});const r=e.duration??8;if(r<=0||r>this.maxDurationSeconds)throw new Kt({code:Yt.INVALID_INPUT,message:`ElevenLabs Music duration must be between 1 and ${this.maxDurationSeconds} seconds; got ${r}`,category:"validation",severity:"low",retriable:!1,context:{requested:r,maximum:this.maxDurationSeconds}});const n=Date.now(),o=r,i={text:this.buildPrompt({...e,prompt:t}),duration_seconds:o,prompt_influence:.3},s=new AbortController,a=setTimeout(()=>s.abort(),Zue);let l;try{l=await fetch(`${this.baseUrl}/sound-generation`,{method:"POST",headers:{"xi-api-key":this.apiKey,"Content-Type":"application/json",Accept:"audio/mpeg"},body:JSON.stringify(i),signal:s.signal})}catch(d){throw d instanceof Error&&d.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`ElevenLabs Music request timed out after ${Zue/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:d}):new Kt({code:Yt.GENERATION_FAILED,message:`ElevenLabs Music network error: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"high",retriable:!0,originalError:d instanceof Error?d:void 0})}finally{clearTimeout(a)}if(!l.ok){const d=await l.text(),p=l.status===408||l.status===429||l.status>=500;throw new Kt({code:Yt.GENERATION_FAILED,message:`ElevenLabs Music synthesis failed: ${l.status} \u2014 ${d}`,category:p?"network":"execution",severity:"high",retriable:p,context:{status:l.status}})}const c=await l0(l,Vh,"ElevenLabs music"),u=Date.now()-n;return h.info(`[ElevenLabsMusic] Generated ${c.length} bytes in ${u}ms`),{buffer:c,format:"mp3",size:c.length,duration:o,provider:"elevenlabs-music",metadata:{latency:u,provider:"elevenlabs-music",model:"elevenlabs-sound-v1"}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}}}}),Jcr,Xcr,Que,AT,Ycr=S({"src/lib/music/providers/LyriaMusic.ts"(){"use strict";qp(),z(),Ft(),Jcr="https://generativelanguage.googleapis.com/v1beta",Xcr="lyria-3-pro-preview",Que=12e4,AT=class{maxDurationSeconds=30;supportedFormats=["wav"];supportedGenres=["ambient","classical","electronic","jazz","rock","pop","lo-fi","cinematic","orchestral","world"];apiKey;baseUrl;model;constructor(e){const t=(e??process.env.GOOGLE_AI_LYRIA_API_KEY??process.env.GOOGLE_API_KEY??process.env.GOOGLE_AI_API_KEY??process.env.GEMINI_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.LYRIA_BASE_URL??Jcr).replace(/\/$/,""),this.model=process.env.LYRIA_MODEL??Xcr}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:"Lyria requires one of: GOOGLE_API_KEY, GOOGLE_AI_LYRIA_API_KEY, GOOGLE_AI_API_KEY, or GEMINI_API_KEY",category:"configuration",severity:"high",retriable:!1});const t=Date.now(),r=Math.min(e.duration??16,this.maxDurationSeconds),o={contents:[{parts:[{text:`${this.buildPrompt(e)}. Duration: ${r} seconds`}]}],generationConfig:{responseModalities:["AUDIO"]}},i=new AbortController,s=setTimeout(()=>i.abort(),Que);let a;try{a=await fetch(`${this.baseUrl}/models/${this.model}:generateContent?key=${this.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i.signal})}catch(p){throw p instanceof Error&&p.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Lyria request timed out after ${Que/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:p}):p}finally{clearTimeout(s)}if(!a.ok){const p=await a.text(),m=a.status===408||a.status===429||a.status>=500;throw new Kt({code:Yt.GENERATION_FAILED,message:`Lyria generation failed: ${a.status} \u2014 ${gr(p)}`,category:m?"network":"execution",severity:"high",retriable:m,context:{status:a.status}})}const l=await a.json(),c=l.candidates?.[0]?.content?.parts?.find(p=>p.inlineData?.mimeType?.startsWith("audio/"));if(!c?.inlineData?.data)throw new Kt({code:Yt.GENERATION_FAILED,message:"Lyria response missing audio data",category:"execution",severity:"high",retriable:!1,context:{response:l}});const u=Buffer.from(c.inlineData.data,"base64"),d=Date.now()-t;return h.info(`[LyriaMusic] Generated ${u.length} bytes in ${d}ms \u2014 model ${this.model}`),{buffer:u,format:"wav",size:u.length,duration:r,provider:"lyria",metadata:{latency:d,provider:"lyria",model:this.model,sampleRate:48e3}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}}}});function Wh(e){const t=(e?.apiToken??process.env.REPLICATE_API_TOKEN??"").trim();return t?{apiToken:t,baseUrl:(e?.baseUrl??process.env.REPLICATE_BASE_URL??Zcr).replace(/\/$/,"")}:null}var Zcr,D$=S({"src/lib/adapters/replicate/auth.ts"(){"use strict";Zcr="https://api.replicate.com"}});async function evn(e,t,r){const n=e.baseUrl??"https://api.replicate.com",[o,i]=t.model.split(":",2),s=i?`${n}/v1/predictions`:`${n}/v1/models/${o}/predictions`,a=i?{version:i,input:t.input}:{input:t.input};return t.webhook&&(a.webhook=t.webhook),t.webhookEventsFilter&&t.webhookEventsFilter.length>0&&(a.webhook_events_filter=t.webhookEventsFilter),Fv(async()=>{const l=new AbortController,c=setTimeout(()=>l.abort(),CT);try{const u=await fetch(s,{method:"POST",headers:{Authorization:`Token ${e.apiToken}`,"Content-Type":"application/json",Prefer:"wait=60"},body:JSON.stringify(a),signal:l.signal});if(!u.ok){const d=await u.text();throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate predictions submit failed: ${u.status} \u2014 ${gr(d,500)}`,category:"network",severity:"high",retriable:u.status>=500||u.status===429,retryAfterMs:Lv(u.headers)})}return await u.json()}catch(u){throw u instanceof Me?u:u instanceof Error&&u.name==="AbortError"?new Me({code:je.OPERATION_ABORTED,message:`Replicate predictions submit timed out after ${CT/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:u}):u}finally{clearTimeout(c)}},void 0,"Replicate prediction submission",r)}async function tvn(e,t,r={}){const n=e.baseUrl??"https://api.replicate.com",o=Date.now(),i=r.timeoutMs??eur,s=r.pollIntervalMs??Qcr;for(;Date.now()-o<i;){if(r.abortSignal?.aborted)throw new Me({code:je.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1});const a=new AbortController,l=setTimeout(()=>a.abort(),CT),c=()=>a.abort();r.abortSignal?.addEventListener("abort",c,{once:!0});let u;try{u=await fetch(`${n}/v1/predictions/${t}`,{method:"GET",headers:{Authorization:`Token ${e.apiToken}`},signal:a.signal})}catch(p){throw p instanceof Me?p:p instanceof Error&&p.name==="AbortError"?r.abortSignal?.aborted?new Me({code:je.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1,originalError:p}):new Me({code:je.OPERATION_ABORTED,message:`Replicate poll request timed out after ${CT/1e3}s`,category:"timeout",severity:"high",retriable:!0,originalError:p}):p}finally{r.abortSignal?.removeEventListener("abort",c),clearTimeout(l)}if(!u.ok){const p=await u.text();throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate poll failed: ${u.status} \u2014 ${gr(p,500)}`,category:"network",severity:"high",retriable:u.status>=500||u.status===429,retryAfterMs:Lv(u.headers)})}const d=await u.json();if(d.status==="succeeded")return d;if(d.status==="failed"||d.status==="canceled")throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${d.id} ${d.status}: ${d.error??"unknown"}`,category:"execution",severity:"high",retriable:d.status==="failed"});await new Promise((p,m)=>{const f=()=>{clearTimeout(g),m(new Me({code:je.OPERATION_ABORTED,message:"Replicate poll aborted by caller",category:"abort",severity:"low",retriable:!1}))},g=setTimeout(()=>{r.abortSignal?.removeEventListener("abort",f),p()},s);r.abortSignal?.addEventListener("abort",f,{once:!0})})}throw new Me({code:je.OPERATION_ABORTED,message:`Replicate prediction ${t} did not complete within ${Math.round(i/1e3)}s`,category:"timeout",severity:"high",retriable:!0})}async function UC(e,t,r={}){const n=await evn(e,t);if(n.status==="succeeded")return n;if(n.status==="failed"||n.status==="canceled")throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${n.id} ${n.status} on submit: ${n.error??"unknown"}`,category:"execution",severity:"high",retriable:n.status==="failed"});return tvn(e,n.id,r)}async function N$(e,t=c0){const r=e.output,n=Array.isArray(r)?r[0]:r;if(typeof n!="string")throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate prediction ${e.id} output is not a URL: ${typeof r}`,category:"execution",severity:"high",retriable:!1});try{const o=await zp(n,{maxBytes:t,label:`Replicate prediction ${e.id}`,timeoutMs:CT});return h.debug(`[Replicate] Downloaded prediction ${e.id} output: ${o.length} bytes`),o}catch(o){if(o instanceof Me)throw o;const i=o instanceof Error?o.message:String(o);throw new Me({code:je.PROVIDER_NOT_AVAILABLE,message:`Replicate output download failed: ${i} \u2014 ${n}`,category:"network",severity:"high",retriable:!0,originalError:o instanceof Error?o:void 0})}}var CT,Qcr,eur,L$=S({"src/lib/adapters/replicate/predictionLifecycle.ts"(){"use strict";z(),et(),Ft(),rp(),NP(),Md(),Ta(),CT=9e4,Qcr=2e3,eur=5*6e4}}),tur,IT,rur=S({"src/lib/music/providers/ReplicateMusic.ts"(){"use strict";qp(),z(),D$(),L$(),Ta(),OC(),tur="meta/musicgen:7be0f12c54a8d033a0fbd14418c9af98962da9a86f5ff7811f9b3423a1f0b7d7",IT=class{maxDurationSeconds=30;supportedFormats=["mp3","wav"];supportedGenres=["ambient","classical","electronic","rock","jazz","hip-hop","pop","lo-fi","cinematic","orchestral"];isConfigured(){return Wh()!==null}async generate(e){const t=Wh();if(!t)throw new Kt({code:Yt.PROVIDER_NOT_CONFIGURED,message:"REPLICATE_API_TOKEN not configured",category:"configuration",severity:"high",retriable:!1});const r=Date.now(),n=e.model??tur,o=e.format??"mp3",i=this.supportedFormats.includes(o)?o:"mp3",s=Math.min(e.duration??8,this.maxDurationSeconds),a={prompt:this.buildPrompt(e),duration:s,output_format:i,model_version:"stereo-large",normalization_strategy:"loudness"};if(e.tempo!==void 0&&(a.bpm=e.tempo),e.referenceAudio){const d=await this.resolveBuffer(e.referenceAudio);a.input_audio=`data:audio/${this.detectAudioType(d)};base64,${d.toString("base64")}`}let l;try{l=await UC(t,{model:n,input:a})}catch(d){throw new Kt({code:Yt.GENERATION_FAILED,message:`Replicate music generation failed: ${d instanceof Error?d.message:String(d)}`,category:"execution",severity:"high",retriable:!0,context:{model:n,duration:s,format:i,hasReferenceAudio:e.referenceAudio!==void 0},originalError:d instanceof Error?d:void 0})}let c;try{c=await N$(l,Vh)}catch(d){throw new Kt({code:Yt.GENERATION_FAILED,message:`Replicate music download failed: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"medium",retriable:!0,context:{predictionId:l.id},originalError:d instanceof Error?d:void 0})}const u=Date.now()-r;return h.info(`[ReplicateMusic] Generated ${c.length} bytes in ${u}ms \u2014 model ${n}`),{buffer:c,format:i,size:c.length,duration:s,provider:"replicate",metadata:{latency:u,provider:"replicate",model:n,jobId:l.id}}}buildPrompt(e){const t=[e.prompt];return e.genre&&t.push(`Genre: ${e.genre}`),e.mood&&t.push(`Mood: ${e.mood}`),e.tempo!==void 0&&t.push(`${e.tempo} BPM`),t.join(". ")}async resolveBuffer(e){if(Buffer.isBuffer(e))return e;if(!/^https:\/\//.test(e))throw new Kt({code:Yt.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await PC(e)}catch(i){throw new Kt({code:Yt.INVALID_INPUT,message:`Unsafe URL rejected: ${i instanceof Error?i.message:String(i)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=6e4,r=new AbortController,n=setTimeout(()=>r.abort(),t);let o;try{o=await fetch(e,{signal:r.signal})}catch(i){throw i instanceof Error&&i.name==="AbortError"?new Kt({code:Yt.GENERATION_FAILED,message:`Replicate music reference-audio fetch timed out after ${t/1e3}s: ${e}`,category:"network",severity:"medium",retriable:!0}):i}finally{clearTimeout(n)}if(!o.ok)throw new Kt({code:Yt.GENERATION_FAILED,message:`Failed to fetch reference audio: ${e}: ${o.status}`,category:"network",severity:"medium",retriable:o.status>=500});try{return await l0(o,Vh,"Replicate reference audio")}catch(i){throw new Kt({code:Yt.INVALID_INPUT,message:`Replicate reference audio too large: ${i instanceof Error?i.message:String(i)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}}}}),ede={};ce(ede,{BeatovenMusic:()=>kT,BeatovenMusicHandler:()=>kT,ElevenLabsMusic:()=>xT,ElevenLabsMusicHandler:()=>xT,LyriaMusic:()=>AT,LyriaMusicHandler:()=>AT,MUSIC_ERROR_CODES:()=>Yt,MusicError:()=>Kt,MusicProcessor:()=>Gp,ReplicateMusic:()=>IT,ReplicateMusicHandler:()=>IT,registerDefaultMusicHandlers:()=>nur});function nur(){for(const{name:e,aliases:t,factory:r}of iur){const n=!Gp.supports(e),o=(t??[]).filter(i=>!Gp.supports(i));if(!(!n&&o.length===0))try{let i;if(n||(i=Gp.getHandler(e)),!i&&(i=r(),!i.isConfigured()))continue;n&&Gp.registerHandler(e,i);for(const s of o)Gp.registerHandler(s,i)}catch(i){h.debug(`[music] ${e} auto-registration skipped: ${i instanceof Error?i.message:String(i)}`)}}}var our,iur,tde=S({"src/lib/music/index.ts"(){"use strict";jv(),z(),qp(),qp(),Hcr(),Kcr(),Ycr(),rur(),Hcr(),Kcr(),Ycr(),rur(),our={beatoven:()=>new kT,"elevenlabs-music":()=>new xT,lyria:()=>new AT,replicate:()=>new IT},iur=op.filter(e=>e.kind==="music").map(e=>{const t=our[e.name];if(!t)throw new Error(`[music] no handler factory for catalog entry "${e.name}"`);return{name:e.name,aliases:e.aliases,factory:t}})}}),sur={};ce(sur,{AVATAR_ERROR_CODES:()=>xt,AvatarError:()=>St,AvatarProcessor:()=>jp});var xt,St,jp,Kh=S({"src/lib/utils/avatarProcessor.ts"(){"use strict";Zn(),et(),z(),bw(),xt={PROVIDER_NOT_SUPPORTED:"AVATAR_PROVIDER_NOT_SUPPORTED",PROVIDER_NOT_CONFIGURED:"AVATAR_PROVIDER_NOT_CONFIGURED",GENERATION_FAILED:"AVATAR_GENERATION_FAILED",POLL_TIMEOUT:"AVATAR_POLL_TIMEOUT",INVALID_INPUT:"AVATAR_INVALID_INPUT",AUDIO_REQUIRED:"AVATAR_AUDIO_REQUIRED",IMAGE_REQUIRED:"AVATAR_IMAGE_REQUIRED",AUDIO_TOO_LONG:"AVATAR_AUDIO_TOO_LONG"},St=class extends Me{constructor(e){super({code:e.code,message:e.message,category:e.category??"execution",severity:e.severity??"high",retriable:e.retriable??!1,context:e.context,originalError:e.originalError}),this.name="AvatarError"}},jp=class{static registry=new Fg("AvatarProcessor");static registerHandler(e,t){const r=e&&e.toLowerCase();this.registry.register(e,t),h.debug(`[AvatarProcessor] Registered avatar handler: ${r}`)}static supports(e){return this.registry.supports(e)}static listProviders(){return this.registry.list()}static getHandler(e){return this.registry.get(e)}static clearHandlers(){this.registry.clear()}static buildSpanAttributes(e,t){return{"avatar.operation":"generate","avatar.provider":e,"avatar.quality":t.quality,"avatar.format":t.format,"avatar.has_text":t.text!==void 0,"avatar.has_audio":t.audio!==void 0}}static async generate(e,t){const r=Ce.createSpan("media.generation","avatar.generate",this.buildSpanAttributes(e,t));try{if(!t.image)throw new St({code:xt.IMAGE_REQUIRED,message:"Avatar generation requires an `image` (Buffer, path, or URL)",category:"validation",severity:"medium",retriable:!1,context:{provider:e}});if(!t.audio&&!t.text)throw new St({code:xt.INVALID_INPUT,message:"Avatar generation requires either `audio` (a Buffer/URL) or `text` (to be TTS'd by the provider).",category:"validation",severity:"high",retriable:!1,context:{provider:e}});const n=this.getHandler(e);if(!n)throw new St({code:xt.PROVIDER_NOT_SUPPORTED,message:`Avatar provider "${e}" is not registered. Available: ${this.listProviders().join(", ")}`,category:"configuration",severity:"high",retriable:!1,context:{provider:e,available:this.listProviders()}});if(!n.isConfigured())throw new St({code:xt.PROVIDER_NOT_CONFIGURED,message:`Avatar provider "${e}" is not configured. Set the required credentials.`,category:"configuration",severity:"high",retriable:!1,context:{provider:e}});h.debug(`[AvatarProcessor] Starting avatar generation with provider: ${e}`);const o=await n.generate(t),i=Ce.endSpan(r,1);return rt().recordSpan(i),h.info(`[AvatarProcessor] Generated ${o.size} bytes (${e})`),o}catch(n){const o=Ce.endSpan(r,2,n instanceof Error?n.message:String(n));if(rt().recordSpan(o),n instanceof St)throw n;const i=n instanceof Error?n.message:String(n);throw new St({code:xt.GENERATION_FAILED,message:`Avatar generation failed for provider "${e}": ${i}`,category:"execution",severity:"high",retriable:!0,context:{provider:e},originalError:n instanceof Error?n:void 0})}}}}}),aur,rde,lur,cur,RT,uur=S({"src/lib/avatar/providers/DIDAvatar.ts"(){"use strict";z(),Ft(),Kh(),OC(),Ta(),aur="https://api.d-id.com",rde=3e4,lur=3e3,cur=5*6e4,RT=class{maxAudioDurationSeconds=60;supportedFormats=["mp4"];apiKey;baseUrl;constructor(e){const t=(e??process.env.DID_API_KEY??process.env.D_ID_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.DID_BASE_URL??process.env.D_ID_BASE_URL??aur).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new St({code:xt.PROVIDER_NOT_CONFIGURED,message:"DID_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});if(!e.audio&&!e.text)throw new St({code:xt.AUDIO_REQUIRED,message:"D-ID requires either `audio` (Buffer/path) or `text` (with voice id) to drive the talk",category:"validation",severity:"medium",retriable:!1});const t=Date.now(),r=await this.uploadImage(e.image),n=e.audio?await this.uploadAudio(e.audio):void 0,o=await this.submitTalk(e,r,n),i=await this.pollUntilDone(o,e.timeout??cur,e.abortSignal);if(!i.result_url)throw new St({code:xt.GENERATION_FAILED,message:`D-ID talk ${o} completed but no result_url returned`,category:"execution",severity:"high",retriable:!1,context:{talkId:o,completed:i}});try{await PC(i.result_url)}catch(l){throw new St({code:xt.GENERATION_FAILED,message:`D-ID result_url rejected as unsafe: ${l instanceof Error?l.message:String(l)}`,category:"validation",severity:"high",retriable:!1,context:{talkId:o,url:i.result_url}})}const s=await this.downloadResult(i.result_url),a=Date.now()-t;return h.info(`[DIDAvatar] Generated ${s.length} bytes in ${a}ms \u2014 talk ${o}`),{buffer:s,format:"mp4",size:s.length,duration:i.duration,provider:"d-id",metadata:{latency:a,provider:"d-id",jobId:o}}}async uploadImage(e){if(typeof e=="string"&&/^https:\/\//.test(e))return e;const t=await this.resolveBuffer(e),r=new FormData;r.append("image",new Blob([new Uint8Array(t)],{type:this.detectImageMime(t)}),"source.png");const n=await this.fetchWithTimeout(`${this.baseUrl}/images`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`},body:r}),o=await this.assertOk(n,"image upload");if(!o.url)throw new St({code:xt.GENERATION_FAILED,message:"D-ID image upload succeeded but returned no URL",category:"execution",severity:"high",retriable:!1});return o.url}async uploadAudio(e){if(typeof e=="string"&&/^https:\/\//.test(e))return e;const t=await this.resolveBuffer(e),r=this.detectAudioType(t),o={mp3:"mp3",mpeg:"mp3",wav:"wav",ogg:"ogg",mp4:"m4a"}[r]??"mp3",i=new FormData;i.append("audio",new Blob([new Uint8Array(t)],{type:`audio/${r}`}),`narration.${o}`);const s=await this.fetchWithTimeout(`${this.baseUrl}/audios`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`},body:i}),a=await this.assertOk(s,"audio upload");if(!a.url)throw new St({code:xt.GENERATION_FAILED,message:"D-ID audio upload succeeded but returned no URL",category:"execution",severity:"high",retriable:!1});return a.url}async submitTalk(e,t,r){const n=r?{type:"audio",audio_url:r}:{type:"text",input:e.text,provider:{type:"microsoft",voice_id:e.voice??"en-US-JennyNeural"}},o={source_url:t,script:n,config:{result_format:"mp4",stitch:!0}},i=await this.fetchWithTimeout(`${this.baseUrl}/talks`,{method:"POST",headers:{Authorization:`Basic ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(o)}),s=await this.assertOk(i,"talk submit");if(!s.id)throw new St({code:xt.GENERATION_FAILED,message:"D-ID talk submit returned no id",category:"execution",severity:"high",retriable:!1});return s.id}async pollUntilDone(e,t,r){const n=Date.now();for(;Date.now()-n<t;){if(r?.aborted)throw new St({code:xt.GENERATION_FAILED,message:`D-ID poll for talk ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{talkId:e}});const o=await this.fetchWithTimeout(`${this.baseUrl}/talks/${e}`,{method:"GET",headers:{Authorization:`Basic ${this.apiKey}`}},r),i=await this.assertOk(o,"talk status");if(i.status==="done")return i;if(i.status==="error"||i.status==="rejected")throw new St({code:xt.GENERATION_FAILED,message:`D-ID talk ${e} ${i.status}: ${i.error?.description??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{talkId:e,status:i.status,error:i.error}});await new Promise((s,a)=>{const l=()=>{clearTimeout(c),a(new St({code:xt.GENERATION_FAILED,message:`D-ID poll for talk ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{talkId:e}}))},c=setTimeout(()=>{r?.removeEventListener("abort",l),s()},lur);r?.addEventListener("abort",l,{once:!0})})}throw new St({code:xt.POLL_TIMEOUT,message:`D-ID talk ${e} did not complete within ${Math.round(t/1e3)}s`,category:"timeout",severity:"medium",retriable:!0,context:{talkId:e}})}async downloadResult(e){const t=await this.fetchWithTimeout(e,{method:"GET"});if(!t.ok)throw new St({code:xt.GENERATION_FAILED,message:`D-ID result download failed: ${t.status}`,category:"network",severity:"medium",retriable:t.status>=500,context:{status:t.status,url:e}});try{return await l0(t,c0,"D-ID result")}catch(r){throw new St({code:xt.GENERATION_FAILED,message:`D-ID result download rejected: ${r instanceof Error?r.message:String(r)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:r instanceof Error?r:void 0})}}async resolveBuffer(e){if(Buffer.isBuffer(e))return e;if(!/^https:\/\//.test(e))throw new St({code:xt.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await PC(e)}catch(n){throw new St({code:xt.INVALID_INPUT,message:`Unsafe URL rejected: ${n instanceof Error?n.message:String(n)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const t=await this.fetchWithTimeout(e,{method:"GET"});if(!t.ok)throw new St({code:xt.INVALID_INPUT,message:`Failed to fetch input from ${e}: ${t.status}`,category:"network",severity:"medium",retriable:t.status>=500,context:{url:e,status:t.status}});const r=Math.max(Vh,Hh);try{return await l0(t,r,"D-ID input")}catch(n){throw new St({code:xt.INVALID_INPUT,message:`D-ID input download rejected: ${n instanceof Error?n.message:String(n)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:n instanceof Error?n:void 0})}}detectImageMime(e){return e.length<4?"image/jpeg":e[0]===137&&e[1]===80?"image/png":e[0]===255&&e[1]===216?"image/jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":"image/jpeg"}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}async fetchWithTimeout(e,t,r){const n=new AbortController,o=setTimeout(()=>n.abort(),rde),i=()=>n.abort();r?.addEventListener("abort",i,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(s){throw s instanceof Error&&s.name==="AbortError"?r?.aborted?new St({code:xt.GENERATION_FAILED,message:`D-ID request to ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,originalError:s}):new St({code:xt.GENERATION_FAILED,message:`D-ID request to ${e} timed out after ${rde/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:s}):s}finally{r?.removeEventListener("abort",i),clearTimeout(o)}}async assertOk(e,t){if(e.ok)return e.json();const r=await e.text(),n=e.status===408||e.status===429||e.status>=500;throw new St({code:xt.GENERATION_FAILED,message:`D-ID ${t} failed: ${e.status} \u2014 ${gr(r,500)}`,category:n?"network":"execution",severity:"high",retriable:n,context:{status:e.status,label:t}})}}}}),dur,F$,pur,nde,MT,mur=S({"src/lib/avatar/providers/HeyGenAvatar.ts"(){"use strict";Kh(),z(),Ft(),Md(),Ta(),dur="https://api.heygen.com/v2",F$=3e4,pur=5e3,nde=5*6e4,MT=class{maxAudioDurationSeconds=300;supportedFormats=["mp4"];apiKey;baseUrl;constructor(e){const t=(e??process.env.HEYGEN_API_KEY??"").trim();this.apiKey=t.length>0?t:null,this.baseUrl=(process.env.HEYGEN_BASE_URL??dur).replace(/\/$/,"")}isConfigured(){return this.apiKey!==null}async generate(e){if(!this.apiKey)throw new St({code:xt.PROVIDER_NOT_CONFIGURED,message:"HEYGEN_API_KEY not configured",category:"configuration",severity:"high",retriable:!1});if(!e.text&&!e.audio)throw new St({code:xt.AUDIO_REQUIRED,message:"HeyGen requires either `text` or `audio` to drive the avatar",category:"validation",severity:"medium",retriable:!1});const t=Date.now(),r=e.abortSignal,n=await this.submitVideo(e),o=await this.pollUntilComplete(n,r),i=await this.download(o),s=Date.now()-t;return h.info(`[HeyGenAvatar] Generated ${i.length} bytes in ${s}ms \u2014 video ${n}`),{buffer:i,format:"mp4",size:i.length,provider:"heygen",metadata:{latency:s,provider:"heygen",jobId:n}}}async submitVideo(e){const t=e,r=t.avatarId??(typeof e.image=="string"&&/^[a-zA-Z0-9_-]{20,}$/.test(e.image)?e.image:void 0);if(!r)throw new St({code:xt.INVALID_INPUT,message:"HeyGen requires `avatarId` (HeyGen avatar catalog id). Pass via options.avatarId or as options.image with a valid HeyGen id.",category:"validation",severity:"medium",retriable:!1});if(e.audio!==void 0){if(Buffer.isBuffer(e.audio))throw new St({code:xt.INVALID_INPUT,message:"HeyGen requires a publicly accessible audio URL; got a binary Buffer. Upload the audio to a hosted location and pass the HTTPS URL instead.",category:"validation",severity:"medium",retriable:!1});if(typeof e.audio!="string"||!/^https?:\/\//i.test(e.audio))throw new St({code:xt.INVALID_INPUT,message:"HeyGen requires a publicly accessible HTTPS audio URL; got an unsupported audio input type. Upload the audio to a hosted location and pass the HTTPS URL instead.",category:"validation",severity:"medium",retriable:!1})}const n=e.audio?{type:"audio",audio_url:e.audio}:{type:"text",input_text:e.text,voice_id:e.voice??"1bd001e7e50f421d891986aad5158bc8"},o={video_inputs:[{character:{type:"avatar",avatar_id:r,avatar_style:"normal"},voice:n,background:{type:"color",value:t.backgroundColor??"#FFFFFF"}}],dimension:{width:t.width??1280,height:t.height??720}},i=await this.fetchWithTimeout(`${this.baseUrl}/video/generate`,{method:"POST",headers:{"X-API-Key":this.apiKey,"Content-Type":"application/json"},body:JSON.stringify(o)});if(!i.ok){const l=await i.text(),c=i.status===408||i.status===429||i.status>=500;throw new St({code:xt.GENERATION_FAILED,message:`HeyGen submit failed: ${i.status} \u2014 ${gr(l,500)}`,category:c?"network":"execution",severity:"high",retriable:c,context:{status:i.status}})}const s=await i.json(),a=s.data?.video_id;if(!a)throw new St({code:xt.GENERATION_FAILED,message:"HeyGen submit response missing video_id",category:"execution",severity:"high",retriable:!1,context:{response:s}});return a}async pollUntilComplete(e,t){const r=Date.now(),n=this.baseUrl.replace(/\/v2$/,"/v1");for(;Date.now()-r<nde;){if(t?.aborted)throw new St({code:xt.GENERATION_FAILED,message:`HeyGen poll for video ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{videoId:e}});const o=await this.fetchWithTimeout(`${n}/video_status.get?video_id=${e}`,{method:"GET",headers:{"X-API-Key":this.apiKey}},t);if(!o.ok){const s=await o.text();throw new St({code:xt.GENERATION_FAILED,message:`HeyGen poll failed: ${o.status} \u2014 ${gr(s,500)}`,category:"network",severity:"medium",retriable:o.status>=500,context:{status:o.status,videoId:e}})}const i=await o.json();if(i.data?.status==="completed"){const s=i.data.video_url;if(!s)throw new St({code:xt.GENERATION_FAILED,message:`HeyGen video ${e} completed but no URL returned`,category:"execution",severity:"high",retriable:!1,context:{videoId:e,data:i}});return s}if(i.data?.status==="failed")throw new St({code:xt.GENERATION_FAILED,message:`HeyGen video ${e} failed: ${i.data?.error?.message??"unknown"}`,category:"execution",severity:"high",retriable:!1,context:{videoId:e,data:i}});await new Promise((s,a)=>{const l=()=>{clearTimeout(c),a(new St({code:xt.GENERATION_FAILED,message:`HeyGen poll for video ${e} aborted by caller`,category:"network",severity:"medium",retriable:!1,context:{videoId:e}}))},c=setTimeout(()=>{t?.removeEventListener("abort",l),s()},pur);t?.addEventListener("abort",l,{once:!0})})}throw new St({code:xt.POLL_TIMEOUT,message:`HeyGen video ${e} did not complete within ${nde/1e3}s`,category:"timeout",severity:"medium",retriable:!0,context:{videoId:e}})}async download(e){try{return await zp(e,{maxBytes:c0,label:"HeyGen video",timeoutMs:F$})}catch(t){throw new St({code:xt.GENERATION_FAILED,message:`HeyGen video download rejected: ${t instanceof Error?t.message:String(t)}`,category:"network",severity:"high",retriable:!1,context:{url:e},originalError:t instanceof Error?t:void 0})}}async fetchWithTimeout(e,t,r){const n=new AbortController;let o=!1;const i=setTimeout(()=>{o=!0,n.abort()},F$),s=()=>n.abort();r?.addEventListener("abort",s,{once:!0});try{return await fetch(e,{...t,signal:n.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?r?.aborted?new St({code:xt.GENERATION_FAILED,message:`HeyGen request to ${e} was aborted by the caller`,category:"network",severity:"medium",retriable:!1,originalError:a}):o?new St({code:xt.GENERATION_FAILED,message:`HeyGen request to ${e} timed out after ${F$/1e3}s`,category:"network",severity:"high",retriable:!0,originalError:a}):new St({code:xt.GENERATION_FAILED,message:`HeyGen request to ${e} was aborted`,category:"network",severity:"high",retriable:!0,originalError:a}):a}finally{r?.removeEventListener("abort",s),clearTimeout(i)}}}}}),hur,PT,fur=S({"src/lib/avatar/providers/ReplicateAvatar.ts"(){"use strict";Kh(),z(),D$(),L$(),Ta(),OC(),hur="douwantech/musetalk:5501004e78525e4bbd9fa20d1e75ad51fddce5a274bec07b9b16d685e34eeaf8",PT=class{maxAudioDurationSeconds=60;supportedFormats=["mp4"];isConfigured(){return Wh()!==null}async generate(e){const t=Wh();if(!t)throw new St({code:xt.PROVIDER_NOT_CONFIGURED,message:"REPLICATE_API_TOKEN not configured",category:"configuration",severity:"high",retriable:!1});if(!e.audio)throw new St({code:xt.AUDIO_REQUIRED,message:"Replicate avatar handler (MuseTalk) requires `audio` (Buffer or path); text-only is not supported. Use D-ID for text-driven talks or chain TTS + Replicate.",category:"validation",severity:"medium",retriable:!1});const r=Date.now(),n=e.model??hur,o=await this.resolveBuffer(e.image,Hh,"Replicate avatar reference image"),i=await this.resolveBuffer(e.audio,Vh,"Replicate avatar reference audio"),s=`data:image/${this.detectImageType(o)};base64,${o.toString("base64")}`,a=`data:audio/${this.detectAudioType(i)};base64,${i.toString("base64")}`;let l;try{l=await UC(t,{model:n,input:{image:s,audio:a,bbox_shift:0,fps:25}})}catch(d){throw new St({code:xt.GENERATION_FAILED,message:`Replicate avatar generation failed: ${d instanceof Error?d.message:String(d)}`,category:"execution",severity:"high",retriable:!0,context:{model:n},originalError:d instanceof Error?d:void 0})}let c;try{c=await N$(l,c0)}catch(d){throw new St({code:xt.GENERATION_FAILED,message:`Replicate avatar download failed: ${d instanceof Error?d.message:String(d)}`,category:"network",severity:"medium",retriable:!0,context:{predictionId:l.id},originalError:d instanceof Error?d:void 0})}const u=Date.now()-r;return h.info(`[ReplicateAvatar] Generated ${c.length} bytes in ${u}ms \u2014 model ${n}`),{buffer:c,format:"mp4",size:c.length,provider:"replicate",metadata:{latency:u,provider:"replicate",model:n,jobId:l.id}}}async resolveBuffer(e,t=Hh,r="Replicate avatar input"){if(Buffer.isBuffer(e)){if(e.length>t)throw new St({code:xt.INVALID_INPUT,message:`${r} too large: ${e.length} bytes exceeds ${t}`,category:"validation",severity:"high",retriable:!1});return e}if(!/^https:\/\//.test(e))throw new St({code:xt.INVALID_INPUT,message:`Invalid input: expected Buffer or HTTPS URL, got string "${e}". Local file reads are not supported.`,category:"validation",severity:"high",retriable:!1});try{await PC(e)}catch(a){throw new St({code:xt.INVALID_INPUT,message:`Unsafe URL rejected: ${a instanceof Error?a.message:String(a)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}const n=6e4,o=new AbortController,i=setTimeout(()=>o.abort(),n);let s;try{s=await fetch(e,{signal:o.signal})}catch(a){throw a instanceof Error&&a.name==="AbortError"?new St({code:xt.INVALID_INPUT,message:`Replicate avatar input fetch timed out after ${n/1e3}s: ${e}`,category:"network",severity:"medium",retriable:!0}):a}finally{clearTimeout(i)}if(!s.ok)throw new St({code:xt.INVALID_INPUT,message:`Failed to fetch ${e}: ${s.status}`,category:"network",severity:"medium",retriable:s.status>=500});try{return await l0(s,t,r)}catch(a){throw new St({code:xt.INVALID_INPUT,message:`${r} too large: ${a instanceof Error?a.message:String(a)}`,category:"validation",severity:"high",retriable:!1,context:{url:e}})}}detectAudioType(e){return e.length<4?"mp3":e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70?"wav":e[0]===79&&e[1]===103&&e[2]===103&&e[3]===83?"ogg":e[0]===73&&e[1]===68&&e[2]===51?"mp3":e[0]===255&&(e[1]&224)===224?"mpeg":e.length>=8&&e[4]===102&&e[5]===116&&e[6]===121&&e[7]===112?"mp4":"mp3"}detectImageType(e){return e.length<4?"jpeg":e[0]===137&&e[1]===80?"png":e[0]===255&&e[1]===216?"jpeg":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"webp":"jpeg"}}}}),ode={};ce(ode,{AVATAR_ERROR_CODES:()=>xt,AvatarError:()=>St,AvatarProcessor:()=>jp,DIDAvatar:()=>RT,DIDAvatarHandler:()=>RT,HeyGenAvatar:()=>MT,HeyGenAvatarHandler:()=>MT,ReplicateAvatar:()=>PT,ReplicateAvatarHandler:()=>PT,registerDefaultAvatarHandlers:()=>gur});function gur(){for(const{name:e,aliases:t,factory:r}of vur){const n=!jp.supports(e),o=(t??[]).filter(i=>!jp.supports(i));if(!(!n&&o.length===0))try{let i;if(n||(i=jp.getHandler(e)),!i&&(i=r(),!i.isConfigured()))continue;n&&jp.registerHandler(e,i);for(const s of o)jp.registerHandler(s,i)}catch(i){h.debug(`[avatar] ${e} auto-registration skipped: ${i instanceof Error?i.message:String(i)}`)}}}var yur,vur,ide=S({"src/lib/avatar/index.ts"(){"use strict";jv(),z(),Kh(),Kh(),uur(),mur(),fur(),uur(),mur(),fur(),yur={"d-id":()=>new RT,heygen:()=>new MT,replicate:()=>new PT},vur=op.filter(e=>e.kind==="avatar").map(e=>{const t=yur[e.name];if(!t)throw new Error(`[avatar] no handler factory for catalog entry "${e.name}"`);return{name:e.name,aliases:e.aliases,factory:t}})}}),OT,$$,sde=S({"src/lib/mcp/elicitation/elicitationManager.ts"(){"use strict";eo(),Bt(),z(),OT=class extends fn{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(const[t,r]of this.pendingRequests)r.settled||(r.settled=!0,this.handleDisabled(r.request,r.resolve),r.timer&&clearTimeout(r.timer),this.pendingRequests.delete(t))}isEnabled(){return this.config.enabled}async request(e){const t={...e,id:e.id??it()};if(!this.config.enabled)return this.handleDisabledRequest(t);const r=t.timeout??this.config.defaultTimeout;return new Promise(n=>{const o=setTimeout(()=>{const i=this.pendingRequests.get(t.id);!i||i.settled||(i.settled=!0,this.handleTimeout(t,n))},r);this.pendingRequests.set(t.id,{request:t,resolve:n,timer:o,settled:!1}),this.emit("elicitationRequested",t),Promise.resolve().then(()=>this.config.handler(t)).then(i=>{const s=this.pendingRequests.get(t.id);!s||s.settled||(s.settled=!0,clearTimeout(o),this.pendingRequests.delete(t.id),this.emit("elicitationResponded",i),n(i))}).catch(i=>{const s=this.pendingRequests.get(t.id);if(!s||s.settled)return;s.settled=!0,clearTimeout(o),this.pendingRequests.delete(t.id);const a={requestId:t.id,responded:!1,error:i instanceof Error?i.message:String(i),timestamp:Date.now()};this.emit("elicitationError",{request:t,error:i}),n(a)})})}async confirm(e,t){const r={type:"confirmation",message:e,toolName:t?.toolName??"unknown",serverId:t?.serverId,confirmLabel:t?.confirmLabel,cancelLabel:t?.cancelLabel,timeout:t?.timeout};return(await this.request(r)).value===!0}async getText(e,t){const r={type:"text",message:e,toolName:t?.toolName??"unknown",placeholder:t?.placeholder,defaultValue:t?.defaultValue,timeout:t?.timeout};return(await this.request(r)).value}async select(e,t,r){const n={type:"select",message:e,toolName:r?.toolName??"unknown",options:t,timeout:r?.timeout};return(await this.request(n)).value}async multiSelect(e,t,r){const n={type:"multiselect",message:e,toolName:r?.toolName??"unknown",options:t,timeout:r?.timeout,minSelections:r?.minSelections,maxSelections:r?.maxSelections};return(await this.request(n)).value}async form(e,t,r){const n={type:"form",message:e,toolName:r?.toolName??"unknown",serverId:r?.serverId,fields:t,submitLabel:r?.submitLabel,timeout:r?.timeout};return(await this.request(n)).value}async getSecret(e,t){const r={type:"secret",message:e,toolName:t?.toolName??"unknown",hint:t?.hint,timeout:t?.timeout};return(await this.request(r)).value}cancel(e,t){const r=this.pendingRequests.get(e);if(r){if(r.settled)return;r.settled=!0,r.timer&&clearTimeout(r.timer);const n={requestId:e,responded:!1,cancelled:!0,error:t,timestamp:Date.now()};r.resolve(n),this.pendingRequests.delete(e),this.emit("elicitationCancelled",{requestId:e,reason:t})}}async defaultHandler(e){return h.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);const r={requestId:e.id,responded:!1,timedOut:!0,value:e.defaultValue,timestamp:Date.now()};this.emit("elicitationTimeout",{request:e}),t(r)}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(const[t]of this.pendingRequests)this.cancel(t,e??"Cleared")}},$$=new OT}}),wur={};ce(wur,{ElicitationManager:()=>OT,globalElicitationManager:()=>$$});var bur=S({"src/lib/mcp/elicitation/index.ts"(){"use strict";sde()}});function yu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ja(e,t){const r=e[t];return typeof r=="string"&&r.length>0?r:void 0}function ade(e,t){const r=e[t];return Array.isArray(r)?r:[]}function BC(e){return e.filter(t=>t!==void 0)}function rvn(e){return e==="localhost"||e==="[::1]"||/^127(?:\.\d{1,3}){3}$/.test(e)}function nvn(e){if(e.type!=="official"&&e.type!=="custom")return;const t=e.url??(e.type==="official"?kur:"");let r;try{r=new URL(t)}catch{return}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.username!==""||r.password!==""||e.authToken&&r.protocol==="http:"&&!rvn(r.hostname))return;const n=r.pathname.replace(/\/+$/,""),o=n.endsWith(lde)?n:`${n}${lde}`;return{config:e,apiBase:`${r.origin}${o}`}}function ovn(e){if(!yu(e))return;const t=Ja(e,"name");return t===void 0?void 0:{name:t,isRequired:e.isRequired===!0,isSecret:e.isSecret===!0}}function Tur(e){if(!yu(e))return;const t=Ja(e,"type");if(t===void 0)return;const r=Ja(e,"url");return r===void 0?{type:t}:{type:t,url:r}}function ivn(e){if(!yu(e))return;const t=Ja(e,"registryType"),r=Ja(e,"identifier");if(t===void 0||r===void 0)return;const n=Ja(e,"version"),o=Tur(e.transport);return{registryType:t,identifier:r,...n===void 0?{}:{version:n},...o===void 0?{}:{transport:o},environmentVariables:BC(ade(e,"environmentVariables").map(ovn))}}function svn(e){if(!yu(e))return;const t=Ja(e,"name");if(t===void 0)return;const r=yu(e.repository)?e.repository:void 0,n=r===void 0?void 0:Ja(r,"url"),o=Ja(e,"websiteUrl");return{name:t,description:Ja(e,"description")??"",version:Ja(e,"version")??"",...n===void 0?{}:{repositoryUrl:n},...o===void 0?{}:{websiteUrl:o},packages:BC(ade(e,"packages").map(ivn)),remotes:BC(ade(e,"remotes").map(Tur))}}function _ur(e){if(!yu(e))return;const t=svn(e.server);if(t===void 0)return;const r=yu(e._meta)?e._meta:void 0,n=r!==void 0?r[xur]:void 0,o=yu(n)?Ja(n,"status"):void 0,i=yu(n)?Ja(n,"updatedAt"):void 0;return{server:t,...o===void 0?{}:{status:o},...i===void 0?{}:{updatedAt:i}}}function avn(e){if(!yu(e)||!Array.isArray(e.servers))throw new Error("registry list response has no servers array");const t=yu(e.metadata)?e.metadata:void 0,r=t===void 0?void 0:Ja(t,"nextCursor");return{records:BC(e.servers.map(_ur)),...r===void 0?{}:{nextCursor:r}}}function Eur(e){switch(e){case"stdio":return"stdio";case"streamable-http":return"http";case"sse":return"sse";default:return}}function lvn(e){if(!(e.registryType!=="npm"||e.identifier.length>Cur||!Aur.test(e.identifier)))return e.version===void 0?e.identifier:e.version.length<=Rur&&Iur.test(e.version)?`${e.identifier}@${e.version}`:void 0}function Sur(e,t){const{server:r}=e,n=r.packages.map(l=>({pkg:l,spec:lvn(l)})).find(l=>l.spec!==void 0),o=Array.from(new Set(BC([...r.packages.map(l=>l.transport===void 0?void 0:Eur(l.transport.type)),...r.remotes.map(l=>Eur(l.type))]))),i=n===void 0?[]:n.pkg.environmentVariables.filter(l=>l.isRequired).map(l=>l.name),s=r.remotes.flatMap(l=>l.url===void 0?[]:[{type:l.type,url:l.url}]),a={source:"remote-registry",registry:t,...e.status===void 0?{}:{registryStatus:e.status},packages:r.packages.map(l=>({registryType:l.registryType,identifier:l.identifier,...l.version===void 0?{}:{version:l.version}})),remotes:s};return{id:r.name,name:r.name,description:r.description,version:r.version,...r.websiteUrl===void 0?{}:{homepage:r.websiteUrl},...r.repositoryUrl===void 0?{}:{repository:r.repositoryUrl},...n===void 0?{}:{npmPackage:n.pkg.identifier,command:"npx",args:["-y",n.spec],installCommand:`npx -y ${n.spec}`},...i.length===0?{}:{requiredEnvVars:i},...o.length===0?{}:{transports:o},...e.updatedAt===void 0?{}:{lastUpdated:e.updatedAt},verified:!1,metadata:a}}var kur,lde,xur,Aur,Cur,Iur,Rur,cvn=S({"src/lib/mcp/mcpRegistryRemote.ts"(){"use strict";kur="https://registry.modelcontextprotocol.io",lde="/v0.1",xur="io.modelcontextprotocol.registry/official",Aur=/^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/,Cur=214,Iur=/^[0-9A-Za-z][0-9A-Za-z.+_~-]*$/,Rur=128}}),Mur={};ce(Mur,{MCPRegistryClient:()=>U$,getAllWellKnownServers:()=>Our,getWellKnownServer:()=>Pur,globalMCPRegistryClient:()=>ude});function Pur(e){return zC.find(t=>t.id===e)}function Our(){return[...zC]}var Dur,Nur,cde,Lur,zC,U$,ude,Fur=S({"src/lib/mcp/mcpRegistryClient.ts"(){"use strict";eo(),z(),cvn(),Dur=100,Nur=5,cde=8*1024*1024,Lur=500,zC=[{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}],U$=class extends fn{config;cache=new Map;customEntries=new Map;constructor(e={}){super(),this.config={registries:[...e.registries??[{type:"official",enableCache:!0}]],remoteLookup:e.remoteLookup??!1,enableCache:e.enableCache??!0,defaultCacheTTL:e.defaultCacheTTL??36e5,timeout:e.timeout??1e4,userAgent:e.userAgent??"NeuroLink-MCP-Registry-Client/1.0"}}async search(e={}){const{query:t,categories:r,tags:n,transport:o,verifiedOnly:i=!1,sortBy:s="downloads",sortDirection:a="desc",limit:l=25,offset:c=0}=e,u=Math.max(1,l),d=Math.max(0,c);let m=[...t?await this.collectEntries(t):await this.getAllEntries()];if(t){const g=t.toLowerCase();m=m.filter(y=>y.name.toLowerCase().includes(g)||y.description.toLowerCase().includes(g)||y.tags?.some(v=>v.toLowerCase().includes(g)))}r?.length&&(m=m.filter(g=>g.categories?.some(y=>r.includes(y)))),n?.length&&(m=m.filter(g=>g.tags?.some(y=>n.includes(y)))),o&&(m=m.filter(g=>g.transports?.includes(o))),i&&(m=m.filter(g=>g.verified)),m.sort((g,y)=>{let v=0;switch(s){case"name":v=g.name.localeCompare(y.name);break;case"downloads":v=(g.downloads??0)-(y.downloads??0);break;case"stars":v=(g.stars??0)-(y.stars??0);break;case"lastUpdated":v=(g.lastUpdated??"").localeCompare(y.lastUpdated??"");break}return a==="desc"?-v:v});const f=m.length;return m=m.slice(d,d+u),{entries:m,totalCount:f,page:Math.floor(d/u)+1,pageSize:u,hasMore:d+m.length<f}}async getEntry(e){if(this.customEntries.has(e))return this.customEntries.get(e);const t=zC.find(r=>r.id===e);if(t)return t;if(this.config.remoteLookup&&!(e===""||e==="."||e===".."))for(const r of this.getRemoteTargets()){const n=await this.fetchRemoteEntry(r,e);if(n)return n}}async getAllEntries(){return this.collectEntries()}async collectEntries(e){const t=e===void 0||!this.config.remoteLookup?"all-entries":`all-entries:${e.toLowerCase()}`,r=this.config.remoteLookup?this.getRemoteTargets():[],n=this.config.enableCache&&r.every(u=>this.isRemoteCacheEnabled(u)),o=Math.min(this.config.defaultCacheTTL,...r.map(u=>u.config.cacheTTL??this.config.defaultCacheTTL)),i=n?this.readCache(t,o):void 0;if(i)return i;const s=new Set(this.customEntries.keys()),a=[...zC.filter(u=>!s.has(u.id)),...Array.from(this.customEntries.values())];let l=a,c=!0;if(this.config.remoteLookup){const u=await Promise.all(r.map(m=>this.fetchRemoteList(m,e))),d=new Set(a.map(m=>m.id)),p=[];for(const m of u){c=c&&m.ok;for(const f of m.entries)d.has(f.id)||(d.add(f.id),p.push(f))}l=[...a,...p]}return n&&c&&this.writeCache(t,l),l}getRemoteTargets(){return this.config.registries.flatMap(e=>{const t=nvn(e);return t===void 0?(ue.debug(`[MCPRegistryClient] Skipping registry of type "${e.type}": not queryable (unsupported type, missing or unusable URL, or a bearer token on plain http to a non-loopback host)`),[]):[t]})}async fetchRemoteEntry(e,t){const r=`remote-entry:${e.apiBase}:${t}`,n=this.readRemoteCache(r,e);if(n)return n;try{const o=await this.requestJson(e,`/servers/${encodeURIComponent(t)}/versions/latest`);if(o.body===void 0)return;const i=_ur(o.body);if(i===void 0||i.status==="deleted"||i.server.name.toLowerCase()!==t.toLowerCase())throw new Error("registry returned no record for the requested server");const s=Sur(i,e.apiBase);return this.writeRemoteCache(r,s,e),s}catch(o){this.reportRemoteError(e,"getEntry",o);return}}async fetchRemoteList(e,t){const r=`remote-list:${e.apiBase}:${(t??"").toLowerCase()}`,n=this.readRemoteCache(r,e);if(n)return{entries:n,ok:!0};try{const o=e.config.maxPages,i=o!==void 0&&Number.isFinite(o)?Math.max(1,Math.floor(o)):Nur,s=[],a=new Set;let l;for(let c=0;c<i;c++){const u=new URLSearchParams({version:"latest",limit:String(Dur)});t&&u.set("search",t),l&&u.set("cursor",l);const d=await this.requestJson(e,"/servers",u),{records:p,nextCursor:m}=avn(d.body);if(s.push(...p.filter(f=>f.status!=="deleted").map(f=>Sur(f,e.apiBase))),m===void 0||a.has(m))break;if(c===i-1){ue.debug(`[MCPRegistryClient] ${e.apiBase}: stopped after ${i} page(s); more servers are available`);break}a.add(m),l=m}return this.writeRemoteCache(r,s,e),{entries:s,ok:!0}}catch(o){return this.reportRemoteError(e,"list",o),{entries:[],ok:!1}}}async requestJson(e,t,r){const n=new URL(`${e.apiBase}${t}`);r?.forEach((s,a)=>n.searchParams.set(a,s));const o={Accept:"application/json","User-Agent":this.config.userAgent,...e.config.authToken?{Authorization:`Bearer ${e.config.authToken}`}:{}},i=await globalThis.fetch(n,{method:"GET",headers:o,signal:AbortSignal.timeout(e.config.timeout??this.config.timeout)});if(i.status===404)return await i.body?.cancel(),{body:void 0};if(!i.ok)throw await i.body?.cancel(),new Error(`registry responded with HTTP ${i.status}`);return{body:await this.readBoundedJson(i)}}async readBoundedJson(e){const t=[];let r=0;if(e.body){const n=e.body.getReader();for(;;){const{done:o,value:i}=await n.read();if(o)break;if(r+=i.byteLength,r>cde)throw await n.cancel(),new Error(`registry response exceeds ${cde} bytes`);t.push(i)}}return JSON.parse(Buffer.concat(t).toString("utf8"))}reportRemoteError(e,t,r){const n=r instanceof Error?r.message:String(r),o=r instanceof Error?r.cause:void 0,i=typeof o=="object"&&o!==null&&"code"in o?String(o.code):void 0,s=i===void 0?n:`${n} (${i})`;ue.debug(`[MCPRegistryClient] ${t} failed for ${e.apiBase}: ${s}`);try{this.emit("registryError",{registry:e.apiBase,operation:t,message:s})}catch(a){ue.debug(`[MCPRegistryClient] registryError listener threw: ${String(a)}`)}}readCache(e,t){const r=this.cache.get(e);return r&&Date.now()-r.timestamp<t?r.data:void 0}readRemoteCache(e,t){return this.isRemoteCacheEnabled(t)?this.readCache(e,t.config.cacheTTL??this.config.defaultCacheTTL):void 0}writeRemoteCache(e,t,r){this.isRemoteCacheEnabled(r)&&this.writeCache(e,t)}isRemoteCacheEnabled(e){return this.config.enableCache&&(e.config.enableCache??!0)}writeCache(e,t){if(!this.cache.has(e)&&this.cache.size>=Lur){const r=this.cache.keys().next();r.done||this.cache.delete(r.value)}this.cache.set(e,{data:t,timestamp:Date.now()})}async getByCategory(e){return(await this.getAllEntries()).filter(r=>r.categories?.includes(e))}async getByTag(e){return(await this.getAllEntries()).filter(r=>r.tags?.includes(e))}async getCategories(){const e=await this.getAllEntries(),t=new Set;for(const r of e)for(const n of r.categories??[])t.add(n);return Array.from(t).sort()}async getTags(){const e=await this.getAllEntries(),t=new Set;for(const r of e)for(const n of r.tags??[])t.add(n);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){const t=this.customEntries.delete(e);return t&&(this.clearCache(),this.emit("entryRemoved",{id:e})),t}addRegistry(e){this.config.registries.push(e),this.clearCache();const{authToken:t,...r}=e;this.emit("registryAdded",{config:r})}setRemoteLookup(e){this.config.remoteLookup=e,this.clearCache(),this.emit("remoteLookupChanged",{enabled:e})}clearCache(){this.cache.clear(),this.emit("cacheCleared")}checkRequiredEnvVars(e){const t=[];for(const r of e.requiredEnvVars??[])process.env[r]||t.push(r);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(){const e=await this.getAllEntries(),t=await this.getCategories(),r=await this.getTags();return{totalEntries:e.length,verifiedEntries:e.filter(n=>n.verified).length,categories:t.length,tags:r.length,customEntries:this.customEntries.size}}},ude=new U$}}),dde={};ce(dde,{AgentExposureManager:()=>G$,exposeAgentAsTool:()=>B$,exposeAgentsAsTools:()=>$ur,exposeWorkflowAsTool:()=>z$,exposeWorkflowsAsTools:()=>Uur,globalAgentExposureManager:()=>pde});function B$(e,t={}){const{prefix:r="agent",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:i=y=>y.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:s=!0,executionTimeout:a=3e5,enableLogging:l=!0}=t,c=i(e.name),u=r?`${r}_${c}`:c;let d=e.description;if(o&&e.metadata){const y=[];e.metadata.version&&y.push(`v${e.metadata.version}`),e.metadata.category&&y.push(`category: ${e.metadata.category}`),e.metadata.estimatedDuration&&y.push(`~${e.metadata.estimatedDuration}ms`),y.length>0&&(d+=` [${y.join(", ")}]`)}const p={...n,complexity:n.complexity??"complex",estimatedDuration:e.metadata?.estimatedDuration??n.estimatedDuration,costHint:e.metadata?.costHint??n.costHint,tags:[...n.tags??[],"agent",...e.metadata?.tags??[]]},m=e.inputSchema??{type:"object",properties:{}},f=async(y,v)=>{const w=Date.now();l&&h.debug(`[AgentExposure] Executing agent '${e.id}' as tool '${u}'`);try{const b=v?.config&&typeof v.config=="object"?v.config:{},E=s?{...v,config:{...b,sourceType:"mcp-exposed-agent",agentId:e.id,toolName:u}}:v??{},k=await Et(e.execute(y,E),a),x=Date.now()-w;return l&&h.debug(`[AgentExposure] Agent '${e.id}' completed in ${x}ms`),{success:!0,data:k,metadata:{agentId:e.id,toolName:u,executionTime:x,sourceType:"agent"}}}catch(b){const E=Date.now()-w,k=b instanceof Error?b:ve.toolExecutionFailed(u,new Error(String(b)));return l&&h.error(`[AgentExposure] Agent '${e.id}' failed after ${E}ms: ${k.message}`),{success:!1,error:k.message,metadata:{agentId:e.id,toolName:u,executionTime:E,sourceType:"agent"}}}};return{tool:{name:u,description:d,inputSchema:m,outputSchema:e.outputSchema,annotations:p,execute:f,metadata:{sourceType:"agent",sourceId:e.id,originalName:e.name,...e.metadata}},sourceType:"agent",sourceId:e.id,toolName:u}}function z$(e,t={}){const{prefix:r="workflow",defaultAnnotations:n={},includeMetadataInDescription:o=!0,nameTransformer:i=y=>y.toLowerCase().replace(/\s+/g,"_"),wrapWithContext:s=!0,executionTimeout:a=6e5,enableLogging:l=!0}=t,c=i(e.name),u=r?`${r}_${c}`:c;let d=e.description;if(o){const y=[];e.metadata?.version&&y.push(`v${e.metadata.version}`),e.steps?.length&&y.push(`${e.steps.length} steps`),e.metadata?.estimatedDuration&&y.push(`~${e.metadata.estimatedDuration}ms`),y.length>0&&(d+=` [${y.join(", ")}]`)}const p={...n,complexity:n.complexity??"complex",estimatedDuration:e.metadata?.estimatedDuration??n.estimatedDuration,idempotentHint:e.metadata?.idempotent??n.idempotentHint,tags:[...n.tags??[],"workflow",...e.metadata?.tags??[]]},m=e.inputSchema??{type:"object",properties:{}},f=async(y,v)=>{const w=Date.now();l&&h.debug(`[WorkflowExposure] Executing workflow '${e.id}' as tool '${u}'`);try{const b=v?.config&&typeof v.config=="object"?v.config:{},E=s?{...v,config:{...b,sourceType:"mcp-exposed-workflow",workflowId:e.id,toolName:u}}:v??{},k=await Et(e.execute(y,E),a),x=Date.now()-w;return l&&h.debug(`[WorkflowExposure] Workflow '${e.id}' completed in ${x}ms`),{success:!0,data:k,metadata:{workflowId:e.id,toolName:u,executionTime:x,sourceType:"workflow",stepsCount:e.steps?.length}}}catch(b){const E=Date.now()-w,k=b instanceof Error?b:ve.toolExecutionFailed(u,new Error(String(b)));return l&&h.error(`[WorkflowExposure] Workflow '${e.id}' failed after ${E}ms: ${k.message}`),{success:!1,error:k.message,metadata:{workflowId:e.id,toolName:u,executionTime:E,sourceType:"workflow"}}}};return{tool:{name:u,description:d,inputSchema:m,outputSchema:e.outputSchema,annotations:p,execute:f,metadata:{sourceType:"workflow",sourceId:e.id,originalName:e.name,steps:e.steps,...e.metadata}},sourceType:"workflow",sourceId:e.id,toolName:u}}function $ur(e,t={}){return e.map(r=>B$(r,t))}function Uur(e,t={}){return e.map(r=>z$(r,t))}var G$,pde,mde=S({"src/lib/mcp/agentExposure.ts"(){"use strict";z(),zr(),et(),G$=class{exposedTools=new Map;options;constructor(e={}){this.options=e}exposeAgent(e){const t=B$(e,this.options);return this.exposedTools.set(t.toolName,t),t.tool}exposeWorkflow(e){const t=z$(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(){const 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)}}},pde=new G$}}),Bur={};ce(Bur,{ToolIntegrationManager:()=>V$,confirmationMiddleware:()=>gde,createElicitationContext:()=>q$,createRetryMiddleware:()=>qur,createTimeoutMiddleware:()=>Gur,createToolMiddlewareChain:()=>hde,globalToolIntegrationManager:()=>vde,loggingMiddleware:()=>fde,validationMiddleware:()=>yde,wrapToolWithElicitation:()=>j$,wrapToolsWithElicitation:()=>zur});function q$(e,t,r){return{confirm:async(n,o)=>r.confirm(n,{toolName:e,serverId:t,confirmLabel:o?.confirmLabel,cancelLabel:o?.cancelLabel}),getText:async(n,o)=>r.getText(n,{toolName:e,placeholder:o?.placeholder,defaultValue:o?.defaultValue}),select:async(n,o)=>r.select(n,o,{toolName:e}),multiSelect:async(n,o)=>r.multiSelect(n,o,{toolName:e}),form:async(n,o)=>r.form(n,o,{toolName:e,serverId:t}),request:async n=>r.request({...n,toolName:e,serverId:t})}}function j$(e,t={}){const{elicitationManager:r,autoConfirmDestructive:n=!1,elicitationTimeout:o=6e4,enableLogging:i=!0}=t,s=r??new OT({defaultTimeout:o});return{...e,execute:async(a,l)=>{const u=l?.config?.serverId,d=q$(e.name,u,s);if((e.annotations?.requiresConfirmation||e.annotations?.destructiveHint)&&!n&&(i&&h.debug(`[ToolIntegration] Tool '${e.name}' requires confirmation`),!await d.confirm(`This operation (${e.name}) ${e.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:e.name,cancelled:!0}};const m={...l,elicitation:d,toolMeta:{name:e.name,serverId:u,annotations:e.annotations}};return e.execute(a,m)}}}function zur(e,t={}){return e.map(r=>j$(r,t))}function hde(e){return async(t,r,n,o)=>{const i=async s=>{if(s>=e.length)return o();const a=e[s];return a(t,r,n,()=>i(s+1))};return i(0)}}function Gur(e){return async(t,r,n,o)=>Be(o(),e,ve.toolTimeout(t.name,e))}function qur(e,t=1e3){return async(r,n,o,i)=>{if(!(r.annotations?.idempotentHint||r.annotations?.readOnlyHint))return i();const a=Math.max(0,e);let l;for(let c=0;c<=a;c++)try{return await i()}catch(u){l=u instanceof Error?u:ve.toolExecutionFailed(r.name,new Error(String(u))),c<a&&(h.warn(`[ToolMiddleware] Tool '${r.name}' failed, retrying (${c+1}/${a})`),await new Promise(d=>setTimeout(d,t*(c+1))))}throw l??ve.toolExecutionFailed(r.name,new Error("Retry middleware exhausted without captured error"))}}var fde,gde,yde,V$,vde,jur=S({"src/lib/mcp/toolIntegration.ts"(){"use strict";sde(),et(),z(),fde=async(e,t,r,n)=>{const o=Date.now();h.debug(`[ToolMiddleware] Executing tool '${e.name}'`);try{const i=await n(),s=Date.now()-o;return h.debug(`[ToolMiddleware] Tool '${e.name}' completed in ${s}ms`),i}catch(i){const s=Date.now()-o;throw h.error(`[ToolMiddleware] Tool '${e.name}' failed after ${s}ms:`,i),i}},gde=async(e,t,r,n)=>r.elicitation?.confirm&&(e.annotations?.destructiveHint||e.annotations?.requiresConfirmation)&&!await r.elicitation.confirm(`Confirm execution of ${e.name}?`)?{success:!1,error:"Operation cancelled by user",metadata:{cancelled:!0}}:n(),yde=async(e,t,r,n)=>{if(!e.inputSchema)return n();const o=e.inputSchema,i=o.required??[],s=o.properties??{},a=t??{},l=[];for(const c of i)a[c]===void 0&&l.push(c);if(l.length>0){const c=l.map(d=>{const p=s[d];return{name:d,label:d,type:p?.type??"text",required:!0,description:p?.description}}),u=await r.elicitation.form(`Missing required parameters for ${e.name}`,c);if(!u)return{success:!1,error:`Missing required parameters: ${l.join(", ")}`,metadata:{missingParams:l}};Object.assign(a,u)}return n()},V$=class{elicitationManager;middlewares=[];wrappedTools=new Map;constructor(e){this.elicitationManager=e??new OT}setElicitationHandler(e){this.elicitationManager.setHandler(e)}use(e){return this.middlewares.push(e),this}registerTool(e){const t=j$(e,{elicitationManager:this.elicitationManager});return this.wrappedTools.set(e.name,t),t}async executeTool(e,t,r){const n=this.wrappedTools.get(e);if(!n)throw ve.toolNotFound(e,Array.from(this.wrappedTools.keys()));const o=t&&typeof t=="object"?t:{},s=r?.config?.serverId,a=q$(e,s,this.elicitationManager),l={...r,elicitation:a,toolMeta:{name:e,serverId:s,annotations:n.annotations}};return this.middlewares.length===0?n.execute(o,l):hde(this.middlewares)(n,o,l,()=>n.execute(o,l))}getTool(e){return this.wrappedTools.get(e)}getAllTools(){return Array.from(this.wrappedTools.values())}getElicitationManager(){return this.elicitationManager}},vde=new V$}}),wde={};ce(wde,{TOOL_COMPATIBILITY:()=>Ede,batchConvertToMCP:()=>Wur,batchConvertToNeuroLink:()=>Kur,createToolFromFunction:()=>Jur,mcpProtocolToolToServerTool:()=>Vur,mcpToolToNeuroLink:()=>Tde,neuroLinkToolToMCP:()=>bde,sanitizeToolName:()=>_de,serverToolToMCPProtocol:()=>Hur,validateToolName:()=>Xur});function bde(e,t={}){const{inferAnnotations:r=!0,defaultAnnotations:n={},preserveMetadata:o=!0,namespacePrefix:i}=t,s=i?`${i}_${e.name}`:e.name,a=r?Ap({name:e.name,description:e.description}):{},l={...n,...a};e.tags?.length&&(l.tags=[...new Set([...l.tags??[],...e.tags])]);const c=e.parameters??{type:"object",properties:{}},u=o?{...e.metadata}:{};return e.category&&(u.category=e.category),e.isAsync!==void 0&&(u.isAsync=e.isAsync),{name:s,description:e.description,inputSchema:c,annotations:l,execute:e.execute,metadata:u}}function Tde(e,t={}){const{removeNamespacePrefix:r}=t;let n=e.name;return r&&e.name.startsWith(`${r}_`)&&(n=e.name.slice(r.length+1)),{name:n,description:e.description,parameters:e.inputSchema,execute:e.execute,category:e.metadata?.category,tags:e.annotations?.tags,metadata:e.metadata}}function Vur(e,t,r={}){const{inferAnnotations:n=!0,defaultAnnotations:o={}}=r,i=e.annotations??{},s=n?Ap({name:e.name,description:e.description??""}):{},a={...o,...s,title:i.title??s.title??o.title,readOnlyHint:i.readOnlyHint??s.readOnlyHint??o.readOnlyHint,destructiveHint:i.destructiveHint??s.destructiveHint??o.destructiveHint,idempotentHint:i.idempotentHint??s.idempotentHint??o.idempotentHint,openWorldHint:i.openWorldHint??s.openWorldHint??o.openWorldHint};return{name:e.name,description:e.description??"No description provided",inputSchema:e.inputSchema,annotations:a,execute:t}}function Hur(e){const t={};e.annotations?.title&&(t.title=e.annotations.title),e.annotations?.readOnlyHint!==void 0&&(t.readOnlyHint=e.annotations.readOnlyHint),e.annotations?.destructiveHint!==void 0&&(t.destructiveHint=e.annotations.destructiveHint),e.annotations?.idempotentHint!==void 0&&(t.idempotentHint=e.annotations.idempotentHint),e.annotations?.openWorldHint!==void 0&&(t.openWorldHint=e.annotations.openWorldHint);const r=e.inputSchema??{type:"object",properties:{}};return{name:e.name,description:e.description,inputSchema:{type:"object",properties:r.properties??{},required:"required"in r?r.required:void 0},annotations:Object.keys(t).length>0?t:void 0}}function Wur(e,t={}){return e.map(r=>bde(r,t))}function Kur(e,t={}){return e.map(r=>Tde(r,t))}function Jur(e,t,r,n){const o=Ap({name:e,description:t});return{name:e,description:t,inputSchema:n?.parameters??{type:"object",properties:{}},annotations:{...o,...n?.annotations},execute:async(i,s)=>await Et(r(i,s),3e4,`Tool '${e}' execution timed out after 30000ms`),metadata:n?.metadata}}function Xur(e){const t=[];return!e||typeof e!="string"?t.push("Tool name is required and must be a string"):(e.length>64&&t.push("Tool name must be 64 characters or less"),/^[a-zA-Z_][a-zA-Z0-9_-]*$/.test(e)||t.push("Tool name must start with a letter or underscore and contain only alphanumeric characters, underscores, and hyphens")),{valid:t.length===0,errors:t}}function _de(e){let t=e.replace(/[^a-zA-Z0-9_-]/g,"_");return/^[a-zA-Z_]/.test(t)||(t=`_${t}`),t.length>64&&(t=t.slice(0,64)),t}var Ede,H$=S({"src/lib/mcp/toolConverter.ts"(){"use strict";WA(),zr(),Ede={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}}}}),DT,d0,Yur,uvn=S({async"src/lib/core/redisConversationMemoryManager.ts"(){"use strict";Vt(),Zt(),Bt(),qx(),hy(),DYt(),wVt(),await bu(),lt(),et(),gb(),z(),xVt(),yN(),S3(),DT=$e.redis,d0=5e3,Yur=class{config;isInitialized=!1;summarizationEngine=new qre;redisConfig;redisClient=null;pendingToolExecutions=new Map;titleGenerationInProgress=new Set;summarizationInProgress=new Set;constructor(e,t={}){this.config=e,this.redisConfig=Mie(t)}async initialize(){if(this.isInitialized){h.debug("[RedisConversationMemoryManager] Already initialized, skipping");return}await DT.startActiveSpan("memory.initialize",{kind:ln.CLIENT,attributes:{"redis.host":this.redisConfig.host,"redis.port":this.redisConfig.port,"redis.key_prefix":this.redisConfig.keyPrefix}},async e=>{try{h.debug("[RedisConversationMemoryManager] Initializing with config",{host:this.redisConfig.host,port:this.redisConfig.port,keyPrefix:this.redisConfig.keyPrefix,ttl:this.redisConfig.ttl}),this.redisClient=await xie(this.redisConfig),this.isInitialized=!0,h.info("RedisConversationMemoryManager initialized",{storage:"redis",host:this.redisConfig.host,port:this.redisConfig.port,maxSessions:this.config.maxSessions,maxTurnsPerSession:this.config.maxTurnsPerSession}),h.debug("[RedisConversationMemoryManager] Redis client created successfully",{clientType:this.redisClient?.constructor?.name||"unknown",isConnected:!!this.redisClient})}catch(t){throw e.setStatus({code:ze.ERROR,message:t instanceof Error?t.message:String(t)}),e.recordException(t instanceof Error?t:new Error(String(t))),h.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 dl("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,r){if(await this.ensureInitialized(),!this.redisClient)return;const n=this.redisClient;return DT.startActiveSpan("memory.getSession",{kind:ln.CLIENT,attributes:{"session.id":e}},async o=>{t&&o.setAttribute("user.id",t);try{const i=fa(this.redisConfig,e,t),s=await Be(n.get(i),d0),a=await this.hydrateMessages(Ha(s||null),i);if(!a){o.setAttribute("session.found",!1);return}o.setAttribute("session.found",!0);const l=s?Buffer.byteLength(s,"utf8"):0,c=a.messages.length,u=!!a.summarizedUpToMessageId,d=u?a.messages.findIndex(m=>m.id===a.summarizedUpToMessageId):-1,p=u&&d!==-1?c-d-1:c;return o.setAttribute("message.count",c),o.setAttribute("blob.size_bytes",l),h.info("[ConversationMemory] Session loaded",{requestId:r,sessionId:e,blobSizeBytes:l,messageCount:c,hasSummary:u,recentMessageCount:p}),l>512*1024&&h.warn("[ConversationMemory] Large session blob",{requestId:r,sessionId:e,blobSizeBytes:l,messageCount:c}),{sessionId:a.sessionId,userId:a.userId,messages:a.messages,summarizedUpToMessageId:a.summarizedUpToMessageId,summarizedMessage:a.summarizedMessage,tokenThreshold:a.tokenThreshold,lastTokenCount:a.lastTokenCount,lastCountedAt:a.lastCountedAt,lastApiTokenCount:a.lastApiTokenCount,createdAt:new Date(a.createdAt).getTime(),lastActivity:new Date(a.updatedAt).getTime()}}catch(i){o.setStatus({code:ze.ERROR,message:i instanceof Error?i.message:String(i)}),o.recordException(i instanceof Error?i:new Error(String(i))),h.error("[RedisConversationMemoryManager] Failed to get session",{sessionId:e,userId:t,error:i instanceof Error?i.message:String(i)});return}finally{o.end()}})}async getSessionRaw(e,t){try{if(await this.ensureInitialized(),!this.redisClient)return null;const r=fa(this.redisConfig,e,t),n=await this.redisClient.get(r);return this.hydrateMessages(Ha(n||null),r)}catch(r){return h.error("[RedisConversationMemoryManager] Failed to get raw session",{sessionId:e,userId:t,error:r instanceof Error?r.message:String(r)}),null}}async getUserSessions(e){if(await this.ensureInitialized(),!this.redisClient)return h.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e}),[];try{const t=Cie(this.redisConfig,e),r=await this.redisClient.sMembers(t);return Array.from(r).map(String)}catch(t){return h.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{const r=Cie(this.redisConfig,e);await qln(this.redisClient,r,t,this.redisConfig.ttl)}catch(r){h.error("[RedisConversationMemoryManager] Failed to add session to user set",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r)})}}async removeUserSession(e,t){if(!this.redisClient||!e)return!1;try{const r=Cie(this.redisConfig,e),n=await this.redisClient.sRem(r,t);return Number(n)>0}catch(r){return h.error("[RedisConversationMemoryManager] Failed to remove session from user set",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r)}),!1}}generateTimestamp(){return new Date().toISOString()}async storeToolExecution(e,t,r,n,o){h.debug("[RedisConversationMemoryManager] Storing tool execution temporarily",{sessionId:e,userId:t,toolCallsCount:r?.length||0,toolResultsCount:n?.length||0});try{const i=t||"randomUser",s=`${e}:${i}`,a={toolCalls:(r||[]).map(c=>({...c,timestamp:o})),toolResults:(n||[]).map(c=>({...c,timestamp:o})),timestamp:Date.now()},l=this.pendingToolExecutions.get(s);l&&(h.debug("[RedisConversationMemoryManager] Merging with existing pending tool data",{sessionId:e,existingToolCalls:l.toolCalls.length,existingToolResults:l.toolResults.length,newToolCalls:r?.length||0,newToolResults:n?.length||0}),a.toolCalls=[...l.toolCalls,...a.toolCalls],a.toolResults=[...l.toolResults,...a.toolResults]),this.pendingToolExecutions.set(s,a),h.debug("[RedisConversationMemoryManager] Tool execution stored temporarily",{sessionId:e,userId:i,pendingKey:s,totalToolCalls:a.toolCalls.length,totalToolResults:a.toolResults.length}),this.cleanupStalePendingData()}catch(i){h.error("[RedisConversationMemoryManager] Failed to store tool execution temporarily",{sessionId:e,error:i instanceof Error?i.message:String(i)})}}async storeConversationTurn(e){return h.debug("[RedisConversationMemoryManager] Storing conversation turn",{sessionId:e.sessionId,userId:e.userId}),await this.ensureInitialized(),DT.startActiveSpan("memory.storeTurn",{kind:ln.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");const r=fa(this.redisConfig,e.sessionId,e.userId),n=await this.redisClient.get(r);let o=await this.hydrateMessages(Ha(n),r);if(SVt(o?.messages??[],e.turnId))return;const i=y1(o),s=o?.messages.length??0,a=new Date().toISOString(),l=e.userId||"randomUser";if(o)o.updatedAt=a;else{const f=`${e.sessionId}:${l}`,g=gt.bind(gt.active(),async()=>{if(!this.titleGenerationInProgress.has(f)){this.titleGenerationInProgress.add(f);try{const y=await this.generateConversationTitle(e.userMessage),v=fa(this.redisConfig,e.sessionId,e.userId||void 0),w=await this.redisClient?.get(v),b=Ha(w||null);if(b){b.title=y,b.updatedAt=new Date().toISOString();const E=Iie(b);this.redisClient&&await Rie(this.redisClient,v,E,this.redisConfig.ttl)}}catch(y){h.warn("[RedisConversationMemoryManager] Failed to generate conversation title in background",{sessionId:e.sessionId,userId:l,error:y instanceof Error?y.message:String(y)})}finally{this.titleGenerationInProgress.delete(f)}}});setImmediate(g),o={id:it(),title:"New Conversation",sessionId:e.sessionId,userId:l,createdAt:e.startTimeStamp?.toISOString()||a,updatedAt:e.startTimeStamp?.toISOString()||a,messages:[]}}const c=e.providerDetails?eVt(e.providerDetails.provider,e.providerDetails.model,this.config.tokenThreshold,o.tokenThreshold):this.config.tokenThreshold||5e4,u={...EVt(TVt(e)),timestamp:e.startTimeStamp?.toISOString()||this.generateTimestamp(),role:"user",content:e.userMessage};o.messages.push(u),await this.flushPendingToolData(o,e.sessionId,l),e.skillMessages&&e.skillMessages.length>0&&o.messages.push(...e.skillMessages);const d={...EVt(_Vt(e,e.thoughtSignature)),timestamp:this.generateTimestamp(),role:"assistant",content:e.aiResponse,events:e.events||void 0};o.messages.push(d),e.tokenUsage&&(o.lastApiTokenCount=e.tokenUsage),h.info("[RedisConversationMemoryManager] Added new messages",{sessionId:o.sessionId,userId:o.userId});const p=e.enableSummarization!==void 0?e.enableSummarization:this.config.enableSummarization;if(await this.persistConversation(o,e.sessionId,e.userId,i?s:void 0),p){const f=e.userId||"randomUser",g=`${e.sessionId}:${f}`;if(this.summarizationInProgress.has(g))h.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:e.sessionId,userId:f});else{const y=gt.bind(gt.active(),async()=>{try{await this.checkAndSummarize(o,c,e.sessionId,e.userId,e.requestId)}catch(v){h.error("Background summarization failed",{sessionId:o.sessionId,error:v instanceof Error?v.message:String(v)})}});setImmediate(y)}}const m=Buffer.byteLength(_3(o),"utf8");h.info("[ConversationMemory] Turn stored",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:m,totalMessages:o.messages.length,userMsgChars:e.userMessage.length,assistantMsgChars:e.aiResponse.length}),m>512*1024&&h.warn("[ConversationMemory] Large session blob",{requestId:e.requestId,sessionId:e.sessionId,blobSizeBytes:m,messageCount:o.messages.length}),e.userId&&await this.addUserSession(e.userId,e.sessionId),t.setAttribute("message.count",o.messages.length),t.setStatus({code:ze.OK}),h.debug("[RedisConversationMemoryManager] Successfully stored conversation turn",{sessionId:e.sessionId,totalMessages:o.messages.length,title:o.title})}catch(r){throw t.setStatus({code:ze.ERROR,message:r instanceof Error?r.message:String(r)}),t.recordException(r instanceof Error?r:new Error(String(r))),new dl(`Failed to store conversation turn in Redis for session ${e.sessionId}`,"STORAGE_ERROR",{sessionId:e.sessionId,error:r instanceof Error?r.message:String(r)})}finally{t.end()}})}async checkAndSummarize(e,t,r,n,o){const i=n||"randomUser",s=`${r}:${i}`;if(this.summarizationInProgress.has(s)){h.debug("[RedisConversationMemoryManager] Summarization already in progress, skipping",{sessionId:r,userId:i});return}this.summarizationInProgress.add(s);try{const a={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()},l=await this.summarizationEngine.checkAndSummarize(a,t,this.config,"[RedisConversationMemoryManager]",o);if(e.lastTokenCount=a.lastTokenCount,e.lastCountedAt=a.lastCountedAt,l&&(e.summarizedUpToMessageId=a.summarizedUpToMessageId,e.summarizedMessage=a.summarizedMessage,this.redisClient)){const c=fa(this.redisConfig,r,n),u=await this.redisClient.get(c);if(u){const d=Ha(u);if(d){d.summarizedUpToMessageId=e.summarizedUpToMessageId,d.summarizedMessage=e.summarizedMessage,d.lastTokenCount=e.lastTokenCount,d.lastCountedAt=e.lastCountedAt;const p=y1(d)?_3(d):Iie(d);await Rie(this.redisClient,c,p,this.redisConfig.ttl)}}}}catch(a){h.error("Token counting or summarization failed",{sessionId:e.sessionId,error:a instanceof Error?a.message:String(a)})}finally{this.summarizationInProgress.delete(s)}}isConversationBlobKey(e){return!Vln(e)&&!e.endsWith(":sessions")&&!e.startsWith(this.redisConfig.userSessionsKeyPrefix)}async hydrateMessages(e,t){if(!e||!y1(e)||!this.redisClient)return e;const r=await Be(this.redisClient.lRange(`${t}${Fb}`,0,-1),d0);return e.messages=Hln(r.map(n=>n.toString())),e}async countMessages(e,t){return!y1(e)||!this.redisClient?e.messages.length:Number(await Be(this.redisClient.lLen(`${t}${Fb}`),d0))}async loadConversation(e,t){if(!this.redisClient)return null;const r=fa(this.redisConfig,e,t);return this.hydrateMessages(Ha(await this.redisClient.get(r)),r)}async persistConversation(e,t,r,n){if(!this.redisClient)return;const o=fa(this.redisConfig,t,r),i=jln(this.redisConfig,t,r),s=this.redisClient.multi();n===void 0&&s.del(i);const a=n===void 0?e.messages:e.messages.slice(n);a.length>0&&s.rPush(i,Wln(a)),s.set(o,_3(e)),this.redisConfig.ttl>0&&(s.expire(o,this.redisConfig.ttl),s.expire(i,this.redisConfig.ttl)),await Be(s.exec(),d0)}async buildContextMessages(e,t,r,n){if(h.debug("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,enableSummarization:r}),await this.ensureInitialized(),!this.redisClient)return h.warn("[RedisConversationMemoryManager] Redis client not available in buildContextMessages"),[];const o=this.redisClient;return DT.startActiveSpan("memory.buildContext",{kind:ln.CLIENT,attributes:{"session.id":e,...t&&{"user.id":t}}},async i=>{try{h.info("[RedisConversationMemoryManager] Building context messages",{sessionId:e,userId:t,method:"buildContextMessages"});const s=fa(this.redisConfig,e,t),a=await Be(o.get(s),d0),l=await this.hydrateMessages(Ha(a||null),s);if(h.debug("[RedisConversationMemoryManager] Retrieved conversation for context building",{sessionId:e,userId:t,conversationFound:!!l}),!l)return i.setAttribute("session.found",!1),i.setStatus({code:ze.OK}),[];const c={sessionId:l.sessionId,userId:l.userId,messages:l.messages,summarizedUpToMessageId:l.summarizedUpToMessageId,summarizedMessage:l.summarizedMessage,tokenThreshold:l.tokenThreshold,lastTokenCount:l.lastTokenCount,lastCountedAt:l.lastCountedAt,createdAt:new Date(l.createdAt).getTime(),lastActivity:new Date(l.updatedAt).getTime()},u=Mre(c,n);h.debug("[RedisConversationMemoryManager] Built context messages from pointer",{sessionId:e,userId:t,contextMessageCount:u.length,pointerMessageId:c.summarizedUpToMessageId||"none"});const d=this.config?.contextCompaction?.sendToolPreview===!0,p=u.map(m=>{if(m.role!=="tool_result")return m;const f=d&&m.metadata?.toolOutputPreview?m.metadata.toolOutputPreview:m.content;let g=m.result;if(m.result&&m.result.result===void 0){let y=f;try{y=JSON.parse(f)}catch{}g={...m.result,result:y}}return h.debug("[RedisConversationMemoryManager] Processing tool_result message for context",{sessionId:e,userId:t,messageId:m.id,sendToolPreview:d,hasPreview:!!m.metadata?.toolOutputPreview,contentLength:f?String(f).length:0,resultHydrated:g!==m.result}),{...m,content:f,result:g}});return i.setAttribute("context.message_count",p.length),i.setStatus({code:ze.OK}),h.info("[RedisConversationMemoryManager] Retrieved context messages",{sessionId:e,userId:t}),p}catch(s){throw i.setStatus({code:ze.ERROR,message:s instanceof Error?s.message:String(s)}),i.recordException(s instanceof Error?s:new Error(String(s))),s}finally{i.end()}})}async getUserSessionMetadata(e,t){if(h.debug("[RedisConversationMemoryManager] Getting user session metadata",{userId:e,sessionId:t}),await this.ensureInitialized(),!this.redisClient)return h.warn("[RedisConversationMemoryManager] Redis client not available",{userId:e,sessionId:t}),null;try{const r=fa(this.redisConfig,t,e),n=await this.redisClient.get(r);if(!n)return h.debug("[RedisConversationMemoryManager] No session data found",{userId:e,sessionId:t,sessionKey:r}),null;const o=Ha(n);return o?{id:o.sessionId,title:o.title,createdAt:o.createdAt,updatedAt:o.updatedAt,metadata:o.additionalMetadata?.agenticLoopReports?{agenticLoopReports:o.additionalMetadata.agenticLoopReports}:void 0}:(h.debug("[RedisConversationMemoryManager] No valid conversation data found",{userId:e,sessionId:t,sessionKey:r}),null)}catch(r){return h.error("[RedisConversationMemoryManager] Failed to get user session metadata",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0}),null}}async getUserSessionHistory(e,t){h.debug("[RedisConversationMemoryManager] Getting user session history via getUserSessionObject",{userId:e,sessionId:t});try{const r=await this.getUserSessionObject(e,t);return r?r.messages:(h.debug("[RedisConversationMemoryManager] No session object found, returning null",{userId:e,sessionId:t}),null)}catch(r){return h.error("[RedisConversationMemoryManager] Failed to get user session history via getUserSessionObject",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"UnknownError",stack:r instanceof Error?r.stack:void 0}),null}}async getUserSessionObject(e,t){if(h.debug("[RedisConversationMemoryManager] Getting complete user session object",{userId:e,sessionId:t,method:"getUserSessionObject"}),!e||typeof e!="string")return h.warn("[RedisConversationMemoryManager] Invalid userId provided",{userId:e,sessionId:t}),null;if(!t||typeof t!="string")return h.warn("[RedisConversationMemoryManager] Invalid sessionId provided",{userId:e,sessionId:t}),null;if(await this.ensureInitialized(),!this.redisClient)return h.warn("[RedisConversationMemoryManager] Redis client not available for getUserSessionObject",{userId:e,sessionId:t}),null;try{const r=fa(this.redisConfig,t,e),n=await this.redisClient.get(r);if(!n)return h.debug("[RedisConversationMemoryManager] No conversation data found in Redis",{userId:e,sessionId:t,sessionKey:r}),null;const o=await this.hydrateMessages(Ha(n),r);return o?!o.messages||!Array.isArray(o.messages)?(h.warn("[RedisConversationMemoryManager] Invalid conversation structure - missing messages array",{userId:e,sessionId:t,hasMessages:!!o.messages,messagesType:typeof o.messages}),null):o:(h.debug("[RedisConversationMemoryManager] Failed to deserialize conversation data",{userId:e,sessionId:t,sessionKey:r,dataLength:n.length}),null)}catch(r){return h.error("[RedisConversationMemoryManager] Failed to get complete user session object",{userId:e,sessionId:t,error:r instanceof Error?r.message:String(r),errorName:r instanceof Error?r.name:"UnknownError",stack:r instanceof Error?r.stack:void 0}),null}}async generateConversationTitle(e){h.info("[RedisConversationMemoryManager] Generating conversation title",{userMessageLength:e.length,userMessagePreview:e.substring(0,100)});try{const t=new GT({conversationMemory:{enabled:!1}}),r=`Generate a clear, concise, and descriptive title (20-25 letters maximum) for a conversation based on the following user message.
1895
1895
  The title must meaningfully reflect the topic or intent of the message.
1896
1896
  Do not output anything unrelated, vague, or generic.
1897
1897
  Do not say you cannot create a title. Always return a valid title.
@@ -539,9 +539,6 @@ export class RedisConversationMemoryManager {
539
539
  messageCount: conversation.messages.length,
540
540
  });
541
541
  }
542
- if (this.redisConfig.ttl > 0) {
543
- await this.redisClient.expire(redisKey, this.redisConfig.ttl);
544
- }
545
542
  if (options.userId) {
546
543
  await this.addUserSession(options.userId, options.sessionId);
547
544
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juspay/neurolink",
3
- "version": "13.8.1",
3
+ "version": "13.8.3",
4
4
  "packageManager": "pnpm@10.15.1",
5
5
  "description": "The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002/call) for routing, tool selection and context budgeting. MCP-native (4 transports), voice TTS/STT/realtime, RAG, agents, memory, compaction, 9 observability exporters. OpenAI · Anthropic · Gemini · Bedrock · Azure · Ollama · TypeSafe Jev and more.",
6
6
  "author": {